LaTeX 初学者指南

LaTeX Beginner's Guide

第二版

Second Edition

伯明翰—孟买

BIRMINGHAM—MUMBAI

LaTeX 初学者指南

LaTeX Beginner's Guide

第二版

Second Edition

版权所有 © 2021 Packt Publishing

Copyright © 2021 Packt Publishing

保留所有权利。未经出版商事先书面许可,不得以任何形式或通过任何方式复制本书的任何部分、将其存储在检索系统中或传播,但在重要文章或评论中嵌入简短引述的情况除外。

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

在准备本书时已尽一切努力确保所提供信息的准确性。但是,本书中包含的信息在出售时没有任何明示或暗示的保证。作者、Packt Publishing 或其经销商和分销商均不对本书直接或间接造成或据称造成的任何损害承担责任。

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.

Packt Publishing 已尽力通过适当使用大写字母来提供有关本书中提及的所有公司和产品的商标信息。但是,Packt Publishing 无法保证此信息的准确性。

Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

集团产品经理:Rohit Rajkumar

Group Product Manager: Rohit Rajkumar

出版产品经理:Ashitosh Gupta

Publishing Product Manager: Ashitosh Gupta

高级编辑:海登·爱德华兹

Senior Editor: Hayden Edwards

内容开发编辑:Rashi Dubey

Content Development Editor: Rashi Dubey

技术编辑:Simran Haresh Udasi

Technical Editor: Simran Haresh Udasi

文案编辑:Safis Editing

Copy Editor: Safis Editing

项目协调员:Manthan Patel

Project Coordinator: Manthan Patel

校对:Safis Editing

Proofreader: Safis Editing

索引器:Manju Arasan

Indexer: Manju Arasan

制作设计:Roshan Kawale

Production Designer: Roshan Kawale

首次发布:2011 年 3 月

First published: March 2011

第二版:2021 年 8 月

Second edition: August 2021

生产编号:1030921

Production reference: 1030921

由 Packt Publishing Ltd 出版。

Published by Packt Publishing Ltd.

制服处

Livery Place

35号衣街

35 Livery Street

伯明翰

Birmingham

B3 2PB,英国。

B3 2PB, UK.

书号 978-1-80107-865-8

ISBN 978-1-80107-865-8

www.packt.com

www.packt.com

感谢 TUG 和 DANTE 的成员支持 TeX 和 LaTeX 的开发、基础设施和教育。感谢 Internet 论坛上的所有帮助者,感谢他们对 LaTeX 初学者的不懈支持。

To the members of TUG and DANTE for supporting TeX and LaTeX development, infrastructure, and education. To all the helpers on internet forums for their tireless support for LaTeX beginners.

– 斯特凡·科特维茨

– Stefan Kottwitz

贡献者

Contributors

关于作者

About the author

Stefan Kottwitz在耶拿和汉堡学习数学。他在 Lufthansa Industry Solutions 和 Eurowings Aviation 担任网络和 IT 安全工程师。

Stefan Kottwitz studied mathematics in Jena and Hamburg. He works as a network and IT security engineer both for Lufthansa Industry Solutions and for Eurowings Aviation.

多年来,他一直在在线论坛上提供 LaTeX 支持。他维护着网络论坛 LaTeX.org 和 goLaTeX.de 以及问答网站 TeXwelt.de 和 TeXnique.fr。他经营着 TeX 图形库站点 TeXample.net、TikZ.net 和 PGFplots.net、TeXlive.net 在线编译器、TeXdoc.org 服务和 CTAN.net 软件镜像。他是 TeX Stack Exchange 网站和 matheplanet.com 的版主。他在他的博客 LaTeX.net 和 TeX.co 上发布来自 TeX 世界的想法和新闻。

For many years, he has been providing LaTeX support on online forums. He maintains the web forums LaTeX.org and goLaTeX.de and the Q&A sites TeXwelt.de and TeXnique.fr. He runs the TeX graphics gallery sites TeXample.net, TikZ.net, and PGFplots.net, the TeXlive.net online compiler, the TeXdoc.org service, and the CTAN.net software mirror. He is a moderator of the TeX Stack Exchange site and matheplanet.com. He publishes ideas and news from the TeX world on his blogs LaTeX.net and TeX.co.

在这本书之前,他于 2011 年撰写了第一版LaTeX 初学者指南,并于 2015 年撰写了LaTeX Cookbook,均由 Packt 出版。

Before this book, he authored the first edition of LaTeX Beginner's Guide in 2011, and LaTeX Cookbook in 2015, both published by Packt.

关于审稿人

About the reviewers

LianTze Lim近二十年来一直陶醉于 LaTeX 排版的乐趣和美妙之中。她目前是 Overleaf 的 Community TeXpert,自 2014 年以来一直在帮助 Overleaf 用户解决与 LaTeX 相关的问题。

LianTze Lim has reveled in the joys and beauty of LaTeX typesetting for nearly two decades. She is currently Community TeXpert at Overleaf and has been helping Overleaf users with LaTeX-related questions since 2014.

Joseph Wright是流行的单位 siunitx 包的作者,领导 beamer 类的维护,并且是 LaTeX 项目的成员。他还是流行的 TeX – LaTeX Stack Exchange Q&A 网站的版主之一。

Joseph Wright is the author of the popular siunitx package for units, leads maintenance of the beamer class, and is a member of the LaTeX project. He is also one of the moderators on the popular TeX – LaTeX Stack Exchange Q&A site.

目录

Table of Contents

前言

Preface

第 1 章:LaTeX 入门

Chapter 1: Getting Started with LaTeX

技术要求

Technical requirements

什么是乳胶?

What is LaTeX?

乳胶的好处

Benefits of LaTeX

开源的优点

Virtues of open source

形式与内容分离

Separation of form and content

可移植性

Portability

保护您的工作

Protection for your work

如何开始使用 LaTeX

How to get started with LaTeX

使用 LaTeX 的方法

Approaches to working with LaTeX

安装和使用 LaTeX

Installing and using LaTeX

使用网络安装程序向导安装 TeX Live

Installing TeX Live using the net installer wizard

离线安装 TeX Live

Installing TeX Live offline

在其他操作系统上安装 TeX Live

Installing TeX Live on other operating systems

更新 TeX Live 并安装新包

Updating TeX Live and installing new packages

创建我们的第一个文件

Creating our first document

检查高级 LaTeX 编辑器

Checking out advanced LaTeX editors

使用 Overleaf 在线使用 LaTeX

Working with LaTeX online using Overleaf

Overleaf 要求和交付的内容

What Overleaf requires and delivers

背页的好处

Benefits of Overleaf

在线工作的注意事项

Caveats of working online

在线创建我们的第一个文档

Creating our first document online

探索背页

Exploring Overleaf

Writefull 的语法和语言反馈

Grammar and language feedback with Writefull

审查和评论

Reviewing and commenting

访问文档

Accessing documentation

概括

Summary

第 2 章:格式化文本和创建宏

Chapter 2: Formatting Text and Creating Macros

技术要求

Technical requirements

使用逻辑格式

Working with logical formatting

创建带有标题和标题的文档

Creating a document with a title and heading

探索文档结构

Exploring the document structure

了解 LaTeX 命令

Understanding LaTeX commands

了解 LaTeX 环境

Understanding LaTeX environments

了解 LaTeX 如何读取我们的输入

Understanding how LaTeX reads our input

打印特殊符号

Printing out special symbols

修改文字字体

Modifying the text fonts

调整字体形状

Adjusting the font shape

选择字体系列

Choosing the font family

用大括号限制命令的效果

Confining the effect of commands by braces

探索字体大小

Exploring font sizes

创建我们自己的命令

Creating our own commands

对简单文本使用宏

Using macros for simple text

命令后的适当间距

Proper spacing after commands

创建更通用的命令和使用参数

Creating more universal commands and using arguments

使用框来限制段落的宽度

Using boxes to limit the width of paragraphs

创建一个窄文本框

Creating a narrow text box

制作通用段落框

Producing common paragraph boxes

探索段落框的更多功能

Exploring further features of paragraph boxes

使用迷你页面

Using mini pages

断行和段落

Breaking lines and paragraphs

改进断字

Improving hyphenation

防止断字

Preventing hyphenation

改进理由

Improving the justification

手动断线

Breaking lines manually

探索换行选项

Exploring line breaking options

防止换行

Preventing line breaks

关闭完全对齐

Turning off full justification

创建右对齐文本

Creating ragged-right text

创建左对齐文本

Creating ragged-left text

居中文本

Centering text

使用环境进行辩护

Using environments for justification

显示报价

Displaying quotes

引用较长的文本

Quoting longer text

概括

Summary

第 3 章:设计页面

Chapter 3: Designing Pages

技术要求

Technical requirements

创建一本书的章节

Creating a book with chapters

定义边距

Defining the margins

使用类选项

Using class options

设计页眉和页脚

Designing headers and footers

了解页面样式

Understanding page styles

自定义页眉和页脚

Customizing headers and footers

在页眉或页脚中使用装饰线

Using decorative lines in headers or footers

更改 LaTeX 的标题标记

Changing LaTeX's header marks

使用脚注

Using footnotes

修改脚注行

Modifying the footnote line

使用包扩展脚注样式

Using packages to expand footnote styles

断页

Breaking pages

放大页面

Enlarging a page

更改行距

Changing the line spacing

创建目录

Creating a table of contents

概括

Summary

第 4 章:创建列表

Chapter 4: Creating Lists

技术要求

Technical requirements

建筑清单

Building lists

创建项目符号列表

Creating a bulleted list

构建枚举列表

Building an enumerated list

生成定义列表

Producing a definition list

自定义列表

Customizing lists

获取紧凑列表

Getting compact lists

选择项目符号和编号格式

Choosing bullets and numbering format

暂停和继续列表

Suspending and continuing lists

概括

Summary

第 5 章:包括图像

Chapter 5: Including Images

技术要求

Technical requirements

包括图像

Including an image

选择最佳文件类型

Choosing an optimal file type

缩放图像

Scaling an image

包括整页

Including whole pages

把图片放在文字后面

Putting images behind the text

管理浮动图像

Managing floating images

了解放置选项

Understanding placement options

强制输出数字

Forcing the output of figures

限制浮动

Limiting floating

完全避免漂浮

Avoiding floating at all

排列多张图片

Arranging several images

让文本围绕图像流动

Letting text flow around images

概括

Summary

第 6 章:创建表

Chapter 6: Creating Tables

技术要求

Technical requirements

使用制表位在列中书写

Using tab stops to write in columns

排版表

Typesetting tables

在表格中画线

Drawing lines in tables

理解格式化参数

Understanding formatting arguments

增加行高

Increasing the row height

美化餐桌

Beautifying tables

调整长度

Adjusting lengths

跨越多列的条目

Spanning entries over multiple columns

按列插入代码

Inserting code column-wise

跨越多行的条目

Spanning entries over multiple rows

向表格添加标题

Adding captions to tables

在上面放置字幕

Placing captions above

自定义字幕

Customizing captions

使用包进行进一步的定制

Using packages for further customizations

自动调整列以适应表格宽度

Auto-fitting columns to the table width

生成多页表

Generating multi-page tables

着色表

Coloring tables

使用横向

Using landscape orientation

在小数点对齐列

Aligning columns at the decimal point

处理窄列

Handling narrow columns

概括

Summary

第 7 章:使用交叉引用

Chapter 7: Using Cross-References

技术要求

Technical requirements

设置标签和参考

Setting labels and references

分配标签

Assigning a label

引用标签

Referring to a label

引用一个页面

Referring to a page

使用高级参考

Using advanced referencing

生成智能页面引用

Producing intelligent page references

微调页面引用

Fine-tuning page references

参考页面范围

Referring to page ranges

使用自动引用名称

Using automatic reference names

将智能引用与自动命名相结合

Combining intelligent references with automatic naming

引用其他文档中的标签

Referring to labels in other documents

将引用变成超链接

Turning references into hyperlinks

概括

Summary

第 8 章:列出内容和参考文献

Chapter 8: Listing Contents and References

技术要求

Technical requirements

自定义目录

Customizing the table of contents

调整 TOC 的深度

Adjusting the depth of the TOC

缩短条目

Shortening entries

手动添加条目

Adding entries manually

创建和自定义图形列表

Creating and customizing lists of figures

创建表列表

Creating a list of tables

使用包进行定制

Using packages for customization

生成索引

Generating an index

定义索引条目和子条目

Defining index entries and subentries

指定页面范围

Specifying page ranges

在索引中使用符号和宏

Using symbols and macros in the index

引用其他索引条目

Referring to other index entries

微调页码

Fine-tuning page numbers

设计索引布局

Designing the index layout

创建参考书目

Creating a bibliography

使用标准书目环境

Using the standard bibliography environment

在 BibTeX 中使用书目数据库

Using bibliography databases with BibTeX

查看 BibTeX 输入字段

Looking at the BibTeX entry fields

参考互联网资源

Referring to Internet resources

了解 BibTeX 条目类型

Understanding BibTeX entry types

选择书目风格

Choosing the bibliography style

列出参考文献而不引用

Listing references without citing

更改标题

Changing the headings

概括

Summary

第 9 章:编写数学公式

Chapter 9: Writing Math Formulas

技术要求

Technical requirements

编写基本公式

Writing basic formulas

在文本中嵌入数学表达式

Embedding math expressions within text

显示公式

Displaying formulas

编号方程式

Numbering equations

添加下标和上标

Adding subscripts and superscripts

使用运算符

Using operators

扎根

Taking roots

写分数

Writing fractions

写希腊字母

Writing Greek letters

写脚本字母

Writing script letters

产生一个省略号

Producing an ellipsis

更改字体、样式和大小

Changing the font, style, and size

自定义显示的公式

Customizing displayed formulas

排版多行公式

Typesetting multi-line formulas

对多行公式中的行进行编号

Numbering rows in multi-line formulas

将文本插入公式

Inserting text into formulas

探索丰富的数学符号

Exploring the wealth of math symbols

二元运算符号

Binary operation symbols

二元关系符号

Binary relation symbols

不等式关系符号

Inequality relation symbols

子集和超集符号

Subset and superset symbols

箭头

Arrows

鱼叉

Harpoons

源自字母的符号

Symbols derived from letters

杂项符号

Miscellaneous symbols

写作单位

Writing units

可变大小运算符

Variable sized operators

可变大小的分隔符

Variable sized delimiters

建立数学结构

Building math structures

创建数组

Creating arrays

排版矩阵

Typesetting matrices

写二项式系数

Writing binomial coefficients

下划线和上划线

Underlining and overlining

设置口音

Setting accents

将一个符号放在另一个符号的上方或下方

Putting a symbol above or below another one

编写定理和定义

Writing theorems and definitions

编写数学的更多工具

Further tools for writing mathematics

概括

Summary

第 10 章:使用字体

Chapter 10: Using Fonts

技术要求

Technical requirements

使用全面的字体包

Using comprehensive font bundles

Latin Modern – 标准字体的替代品

Latin Modern – a replacement for the standard font

Kp-Fonts – 另一组广泛的字体

Kp-Fonts – another extensive set of fonts

使用特定的字体系列

Using specific font families

衬线字体

Serif fonts

无衬线字体

Sans-serif fonts

打字机字体

Typewriter fonts

书法字体

Calligraphic fonts

使用任意字体

Using arbitrary fonts

选择主要字体

Selecting the main font

选择多个字体系列

Selecting multiple font families

概括

Summary

第 11 章:开发大型文档

Chapter 11: Developing Large Documents

技术要求

Technical requirements

拆分输入

Splitting the input

包括小段代码

Including small pieces of code

包括文档的较大部分

Including bigger parts of a document

编译文件的一部分

Compiling parts of a document

创建正面和背面材料

Creating front and back matter

设计标题页

Designing a title page

使用模板

Working with templates

概括

Summary

第 12 章:进一步增强文档

Chapter 12: Enhancing Your Documents Further

技术要求

Technical requirements

使用超链接和书签

Using hyperlinks and bookmarks

添加超链接

Adding hyperlinks

自定义超链接

Customizing hyperlinks

手动创建超链接

Creating hyperlinks manually

手动创建书签

Creating bookmarks manually

在书签中使用数学公式和特殊符号

Using math formulas and special symbols in bookmarks

设计标题

Designing headings

给我们的文件上色

Coloring our documents

概括

Summary

第 13 章:故障排除

Chapter 13: Troubleshooting

技术要求

Technical requirements

理解和修复错误

Understanding and fixing errors

处理序言和文件主体

Handling the preamble and document body

使用命令和环境

Using commands and environments

写数学公式

Writing math formulas

使用文件

Working with files

创建表和数组

Creating tables and arrays

使用列表

Working with lists

使用浮动图形和表格

Working with floating figures and tables

一般语法错误

General syntax errors

处理警告

Handling warnings

对齐文本

Justifying text

引用

Referencing

选择字体

Choosing fonts

放置图形和表格

Placing figures and tables

自定义文档类

Customizing the document class

避免过时的类和包

Avoiding obsolete classes and packages

一般故障排除

General troubleshooting

概括

Summary

第 14 章:使用在线资源

Chapter 14: Using Online Resources

网络论坛、问答网站和讨论区

Web forums, Q&A sites, and discussion boards

LaTeX 网站

LaTeX.org

Stack Exchange 上的 TeX 和 LaTeX

TeX and LaTeX on Stack Exchange

其他语言的论坛

Forums in other languages

新闻组

Usenet groups

常见问题列表

Lists of frequently asked questions

邮件列表

Mailing lists

TeX 用户组站点

TeX user group sites

TeX 用户组

The TeX Users Group

但丁

DANTE

乳胶项目

The LaTeX project

UK TUG——英国的 TeX

UK TUG – TeX in the United Kingdom

其他本地用户组

Other local user groups

LaTeX 软件和编辑器的网站

Websites for LaTeX software and editors

LaTeX 发行版

LaTeX distributions

LaTeX 编辑器

LaTeX editors

CTAN – 全面的 TeX 档案网络

CTAN – the Comprehensive TeX Archive Network

图片库

Graphics galleries

LaTeX 博客

LaTeX blogs

推特消息

Twitter messages

概括

Summary

为什么要订阅?

Why subscribe?

您可能喜欢的其他书籍

Other Books You May Enjoy

Packt 正在寻找像您这样的作者

Packt is searching for authors like you

前言

Preface

LaTeX 是一款高质量的开源排版软件,可制作专业的印刷品和 PDF 文件。然而,由于 LaTeX 是一个强大而复杂的工具,入门可能会令人望而生畏,而且布局修改等具体方面可能看起来相当复杂。使用 Microsoft Word 或其他文字处理软件可能看起来更简单,但是一旦您熟悉了,LaTeX 的功能就远远超过了最初的任何困难。本书将指导您应对这些挑战,让您轻松开始使用 LaTeX。如果您正在撰写数学、科学或技术论文,那么这本书非常适合您。

LaTeX is a high-quality open source typesetting software that produces professional prints and PDF files. However, as LaTeX is a powerful and complex tool, getting started can be intimidating, and specific aspects such as layout modifications can seem rather complicated. Using Microsoft Word or other word-processing software may seem more straightforward, but once you've become acquainted, LaTeX's capabilities far outweigh any initial difficulties. This book guides you through these challenges and makes beginning with LaTeX easy. If you are writing mathematical, scientific, or technical papers, this is the perfect book for you.

LaTeX Beginner's Guide Second Edition 为您提供 LaTeX 的实用介绍。从安装和基本使用开始,您将学习排版包含表格、图形、公式和常见书籍元素(如参考书目、词汇表和索引)的文档。许多分步示例从微调文本、公式和页面布局开始,然后继续管理复杂文档和使用现代 PDF 功能。当您手头有 LaTeX 初学者指南第二版时,就很容易开始使用 LaTeX。

LaTeX Beginner's Guide Second Edition offers you a practical introduction to LaTeX. Beginning with the installation and basic usage, you will learn to typeset documents containing tables, figures, formulas, and common book elements such as bibliographies, glossaries, and indexes. Lots of step-by-step examples start with fine-tuning text, formulas, and page layout, and proceed with managing complex documents and using modern PDF features. It's easy to start with LaTeX when you have LaTeX Beginner's Guide Second Edition at hand.

这本实用的书将引导您完成 LaTeX 的基本步骤,从安装 LaTeX、格式化和对齐到页面设计。从一开始,您将学习使用宏和样式来保持一致的文档结构,同时节省打字工作。本书将帮助您学习创建具有专业外观的表格,以及包括图形和编写复杂的数学公式。您将看到如何轻松地生成参考书目和索引。最后,您将学习如何管理复杂文档以及如何从现代 PDF 功能中获益。有关在线资源(如软件档案、网络论坛和在线编译器)的详细信息补充了本介绍性指南。

This practical book will guide you through the essential steps of LaTeX, from installing LaTeX, formatting, and justification, to page design. Right from the beginning, you will learn to use macros and styles to maintain a consistent document structure while saving typing work. This book will help you learn to create professional-looking tables, along with including figures and writing complex mathematical formulas. You will see how to generate bibliographies and indexes with ease. Finally, you will learn how to manage complex documents and how to benefit from modern PDF features. Detailed information about online resources such as software archives, web forums, and online compilers complement this introductory guide.

这本书是给谁的

Who this book is for

如果您打算撰写数学或科学论文、研讨会讲义,甚至计划撰写论文,那么本书可为您提供快节奏且实用的介绍。那些在学校和大学学习的数学家或物理学家以及工程师和人文学科的学生将受益匪浅。任何抱有很高期望并计划撰写论文或书籍的人都会对这款高质量、稳定的软件感到满意。

If you are about to write mathematical or scientific papers, seminar handouts, or even plan to write a thesis, then this book offers you a fast-paced and practical introduction. Those studying in school and university as mathematicians or physicists will benefit greatly, as well as engineers and humanities students. Anybody with high expectations who plans to write a paper or a book will be delighted by this high-quality, stable software.

本书涵盖的内容

What this book covers

第 1 章 LaTeX 入门,介绍了 LaTeX 并解释了它的优点。它会指导您下载和安装完整的 LaTeX 发行版,并向您展示如何创建您的第一个 LaTeX 文档。还介绍了在线LaTeX软件Overleaf的使用。此外,您将熟悉访问包文档。

Chapter 1, Getting Started with LaTeX, introduces LaTeX and explains its benefits. It guides you through the download and installation of a comprehensive LaTeX distribution and shows you how to create your first LaTeX document. It also introduces the use of the online LaTeX software Overleaf. Furthermore, you will get familiar with accessing package documentation.

第 2 章格式化文本和创建宏,解释了如何改变字体、形状和文本样式。它涉及段落的居中和对齐以及我们如何改进换行和连字符。它介绍了逻辑格式并描述了如何定义宏以及如何使用环境和包。

Chapter 2, Formatting Text and Creating Macros, explains how to vary font, shape, and text styles. It deals with centering and justification of paragraphs and how we can improve line breaks and hyphenation. It introduces logical formatting and describes how to define macros and how to use environments and packages.

第 3 章设计页面,展示了如何调整页边距和更改行距。它演示了纵向、横向和两列布局。在本章中,我们将创建动态页眉和页脚,并学习如何控制分页和如何使用脚注。在此过程中,您还将学习如何重新定义现有命令和使用类选项。

Chapter 3, Designing Pages, shows how you can adjust the margins and change the line spacing. It demonstrates portrait, landscape, and two-column layouts. In this chapter, we will create dynamic headers and footers and learn how to control page breaking and how to use footnotes. Along the way, you will also learn about redefining existing commands and using class options.

第 4 章创建列表,处理在项目符号列表、编号列表和定义列表中排列文本。您将学习如何选择项目符号和编号样式以及如何设计列表的整体布局。

Chapter 4, Creating Lists, deals with arranging text in bulleted, numbered, and definition lists. You will learn how to choose bullets and numbering styles and how to design the overall layout of lists.

第 5 章包括图像,向您展示如何在文档中包括带标题的外部图片。您将学习如何从 LaTeX 的自动图形放置中获益以及如何对其进行微调。

Chapter 5, Including Images, shows you how to include external pictures with captions in your documents. You will learn how to benefit from LaTeX's automated figures placement and how to fine-tune it.

第 6 章创建表格,向您展示如何创建具有专业外观的表格并深入探讨格式设置的详细信息。

Chapter 6, Creating Tables, shows you how to create professional-looking tables and goes deep into formatting details.

第 7 章使用交叉引用,介绍了对部分、脚注、表格、图形和一般编号环境的智能引用。

Chapter 7, Using Cross-References, introduces intelligent referencing to sections, footnotes, tables, figures, and numbered environments in general.

第 8 章列出目录和参考,涉及创建和自定义目录以及图表列表。此外,它还解释了如何引用书籍、创建参考书目和生成索引。

Chapter 8, Listing Contents and References, deals with creating and customizing a table of contents and lists of figures and tables. Furthermore, it explains how to cite books, create bibliographies, and generate an index.

第 9 章编写数学公式,深入解释了数学排版。它从基本公式开始,然后是居中和编号的方程式。它显示了如何对齐多线方程。它详细说明了如何排版数学符号,例如根、箭头、希腊字母和运算符。此外,您将学习构建复杂的数学结构,例如分数、堆叠表达式和矩阵。

Chapter 9, Writing Math Formulas, explains mathematical typesetting in depth. It starts with basic formulas and continues with centered and numbered equations. It shows how to align multi-line equations. In detail, it shows how to typeset math symbols such as roots, arrows, Greek letters, and operators. Moreover, you will learn to build complex math structures such as fractions, stacked expressions, and matrices.

第 10 章使用字体,带我们进入字体世界并演示各种字体,包括不同形状的罗马字体、无衬线字体和打字机字体。

Chapter 10, Using Fonts, takes us into the world of fonts and demonstrates various fonts, including Roman, sans-serif, and typewriter fonts, in different shapes.

第 11 章开发大型文档,通过将大型文档拆分为多个文件来帮助管理大型文档。阅读本章后,您将能够创建基于子文件的复杂项目。此外,我们使用不同的页码和单独的标题页来处理前题和后题。我们将通过创建示例书来解决这个问题。通过这样做,您将熟悉使用文档模板,最后您可以编写自己的论文、书籍或报告。

Chapter 11, Developing Large Documents, helps in managing large documents by splitting them into several files. After reading this chapter, you will be able to create complex projects building upon sub-files. Furthermore, we deal with front matter and back matter with different page numbering and separate title pages. We will work through this by creating an example book. By doing this, you will get familiar with using document templates, and finally you can write your own thesis, book, or report.

第 12 章进一步增强您的文档,为您的文档增添色彩。它向您展示了如何修改章节和各种章节的标题。我们将学习如何创建带有书签、超链接和元数据的功能丰富的 PDF 文档。

Chapter 12, Enhancing Your Documents Further, brings color into your documents. It shows you how to modify headings of chapters and all kinds of sections. We will learn how to create feature-rich PDF documents with bookmarks, hyperlinks, and metadata.

第 13 章故障排除,为我们提供了解决问题的工具。我们将了解不同类型的 LaTeX 错误和警告以及如何处理它们。阅读本章后,您将了解 LaTeX 的消息并知道如何使用它们来修复错误。

Chapter 13, Troubleshooting, provides us with tools for problem-solving. We will learn about different kinds of LaTeX errors and warnings and how to deal with them. After reading this chapter, you will understand LaTeX's messages and know how to use them to fix errors.

第 14 章使用在线资源,引导您浏览互联网上大量的 LaTeX 信息。我们将访问在线 LaTeX 论坛和 LaTeX 问答网站。本章为巨大的 LaTeX 软件档案、TeX 用户组的主页、邮件列表、Usenet 组和 LaTeX 图形库指明了方向。它告诉您在哪里可以下载支持 LaTeX 的编辑器,以及可以在博客和 Twitter 上结识 LaTeX 朋友。

Chapter 14, Using Online Resources, guides you through the vast amount of LaTeX information on the internet. We will visit an online LaTeX forum and a LaTeX Q&A site. This chapter points the way to the huge LaTeX software archives, TeX user groups' homepages, mailing lists, Usenet groups, and LaTeX graphics galleries. It tells you where you can download LaTeX-capable editors and where you can meet LaTeX friends on blogs and Twitter.

为了充分利用本书

To get the most out of this book

您需要访问一台装有 LaTeX 的计算机。在线连接将有助于安装和更新。我们可以在大多数操作系统上安装 LaTeX,因此您可以使用 Windows、Linux、macOS 或 Unix。

You need access to a computer with LaTeX on it. An online connection would be helpful regarding installation and updates. We can install LaTeX on most operating systems, so you can use Windows, Linux, macOS, or Unix.

本书使用免费提供的 TeX Live 发行版,它可以在所有提到的平台上运行。你只需要一个互联网连接或 TeX Live DVD 来安装它。在本书中,我们使用跨平台编辑器 TeXworks,但您可以使用任何您喜欢的编辑器。

This book uses the freely available TeX Live distribution, which runs on all mentioned platforms. You just need an internet connection or the TeX Live DVD to install it. In the book, we work with the cross-platform editor TeXworks, but you could use any editor you like.

在不安装 LaTeX 的情况下,您可以使用https://latexguide.org上的代码示例,它带有一个在线编译器。

Without installing LaTeX, you can work with the code examples at https://latexguide.org, which comes with an online compiler.

如果您使用本书的数字版本,我们建议您自己键入代码或从本书的 GitHub 存储库访问代码(下一节提供链接)。这样做将帮助您避免与复制和粘贴代码相关的任何潜在错误。

If you are using the digital version of this book, we advise you to type the code yourself or access the code from the book's GitHub repository (a link is available in the next section). Doing so will help you avoid any potential errors related to the copying and pasting of code.

下载示例代码文件

Download the example code files

您可以从 GitHub 下载本书的示例代码文件,网址为https://github.com/PacktPublishing/LaTeX-Beginner-s-Guide-Second-Edition。如果代码有更新,它将在 GitHub 存储库中更新。

You can download the example code files for this book from GitHub at https://github.com/PacktPublishing/LaTeX-Beginner-s-Guide-Second-Edition. If there's an update to the code, it will be updated in the GitHub repository.

该书的网站https://latexguide.org也提供代码下载。您还可以访问https://latex-cookbook.net,它提供了带有在线编译器的更完整的代码示例。

The book's website at https://latexguide.org offers code downloads as well. You may also visit https://latex-cookbook.net, which provides further complete code examples with an online compiler.

我们还提供丰富的书籍和视频目录中的其他代码包,网址为https://github.com/PacktPublishing/。去看一下!

We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

使用的约定

Conventions used

本书中使用了许多文本约定。

There are a number of text conventions used throughout this book.

文本中的代码:表示文本中的代码字、数据库表名称、文件夹名称、文件名、文件扩展名、路径名、虚拟 URL、用户输入和 Twitter 句柄。这是一个示例:“加载fontenc包并选择 T1 字体编码。”

Code in text: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an example: "Load the fontenc package and choose T1 font encoding."

一段代码设置如下:

A block of code is set as follows:

\[

\[

  \int_a^b \! f(x) \, dx = \lim_{\Delta x \rightarrow 0}

  \int_a^b \! f(x) \, dx = \lim_{\Delta x \rightarrow 0}

  \sum_{i=1}^{n} f(x_i) \,\Delta x_i

  \sum_{i=1}^{n} f(x_i) \,\Delta x_i

\]

\]

当我们希望将您的注意力吸引到代码块的特定部分时,相关行或项目将以粗体显示:

When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

\文档类{书籍}

\documentclass{book}

\usepackage{cleveref}

\usepackage{cleveref}

\crefname{enumi}{position}{positions}

\crefname{enumi}{position}{positions}

\开始{文档}

\begin{document}

\chapter{统计}

\chapter{Statistics}

\标签{统计}

\label{stats}

\section{LaTeX.org 用户最常用的软件包}

\section{Most used packages by LaTeX.org users}

\标签{包}

\label{packages}

粗体:表示新术语、重要词或您在屏幕上看到的词。例如,菜单或对话框中的单词以粗体显示。下面是一个示例:“单击排版按钮编译文档。”

Bold: Indicates a new term, an important word, or words that you see onscreen. For instance, words in menus or dialog boxes appear in bold. Here is an example: "Click the Typeset button to compile the document."

提示或重要说明

Tips or important notes

出现这个样子。

Appear like this.

保持联系

Get in touch

我们随时欢迎读者的反馈。

Feedback from our readers is always welcome.

一般反馈:如果您对本书的任何方面有疑问,请发送电子邮件至customercare@packtpub.com并在邮件主题中提及书名。

General feedback: If you have questions about any aspect of this book, email us at customercare@packtpub.com and mention the book title in the subject of your message.

LaTeX 问题:如果您对 LaTeX 有任何疑问,可以访问作者的论坛https://latex.org

LaTeX questions: If you have any question about LaTeX, you can visit the author's forum at https://latex.org

勘误表:尽管我们已竭尽全力确保内容的准确性,但错误还是时有发生。如果您在本书中发现错误,请向我们报告,我们将不胜感激。请访问www.packtpub.com/support/errata并填写表格。

Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packtpub.com/support/errata and fill in the form.

盗版:如果您在互联网上发现任何形式的非法复制我们的作品,请提供位置地址或网站名称,我们将不胜感激。请通过copyright@packt.com与我们联系并提供材料链接。

Piracy: If you come across any illegal copies of our works in any form on the internet, we would be grateful if you would provide us with the location address or website name. Please contact us at copyright@packt.com with a link to the material.

如果您有兴趣成为一名作者:如果有一个主题是您的专长,并且您有兴趣撰写或投稿一本书,请访问authors.packtpub.com

If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.

第 1 章:LaTeX 入门

Chapter 1: Getting Started with LaTeX

您熟悉文字处理软件:您键入内容,软件会按屏幕上显示的内容打印出来。相比之下,LaTeX 作为排版软件,从您那里接收指令和文本,然后创建输出。它基于用于对齐、文本对齐、空白平衡、图形放置等的复杂算法生成高质量的输出,例如标题的预定义格式样式和您可以自定义的一般页面布局。

You are familiar with word processing software: you type something, and the software prints it as it is on screen. In contrast, LaTeX, as typesetting software, receives instructions and text from you, and then creates the output. It produces high-quality output based on sophisticated algorithms for justification, text alignment, whitespace balancing, figure placement, and more, such as predefined formatting styles for headings and general page layout, which you can customize.

您准备好离开那些“所见即所得”的文字处理器,进入准确、可靠和高质量排版的世界了吗?是的?那我们一起去吧!

Are you ready to leave those "what you see is what you get" word processors behind and to enter the world of accurate, reliable, and high-quality typesetting? Yes? Then let's go together!

很高兴您决定学习 LaTeX。本书将一路引导您,帮助您充分利用它。让我们简单谈谈 LaTeX 的好处和挑战,然后我们将准备我们的工具。

It's great that you decided to learn LaTeX. This book will guide you along the way to help you get the most out of it. Let's speak briefly about LaTeX's benefits and the challenges, and then we shall prepare our tools.

在本章中,我们将了解 LaTeX,以及如何安装和使用它。具体来说,我们的主题如下:

In this chapter, we will get to know LaTeX, as well as how to install and use it. Specifically, our topics will be as follows:

  • 什么是乳胶?
  • What is LaTeX?
  • 安装和使用 LaTeX
  • Installing and using LaTeX
  • 使用 Overleaf 在线使用 LaTeX
  • Working with LaTeX online using Overleaf
  • 访问文档
  • Accessing documentation

在本章结束时,您将拥有可用的 LaTeX 软件,并且您将了解如何编辑和排版文档以及如何获取更多文档。

At the end of this chapter, you will have working LaTeX software, and you will know how to edit and typeset a document and how to obtain further documentation.

那么,让我们开始吧。

So, let's get started.

技术要求

Technical requirements

我们将在这里重点介绍 Windows 操作系统,但您也可以在 Mac OS X、Linux 和其他系统上安装 LaTeX。

We will focus on the Windows operating system here, but you can also install LaTeX on Mac OS X, Linux, and other systems.

完整安装大约需要 8 GB 的磁盘空间。

A complete installation takes about 8 GB of disk space.

如果您有互联网连接,则不必安装 LaTeX。您可以使用在线 LaTeX 软件,例如 Overleaf。我们将在本章末尾查看 Overleaf。

If you have an internet connection, you don't have to install LaTeX. You can use online LaTeX software, such as Overleaf. We will look at Overleaf at the end of this chapter.

本书的所有代码示例都可以在 GitHub 上找到,网址为https://github.com/PacktPublishing/LaTeX-Beginner-s-Guide

All code examples of this book are available on GitHub at https://github.com/PacktPublishing/LaTeX-Beginner-s-Guide.

在本书的网站 https://latexguide.org 上,您可以在线阅读、编辑和编译本书中的每个代码示例,而无需安装任何东西。为此,您只需要一个启用了 JavaScript 的互联网浏览器,以及一台 PC、笔记本电脑、平板电脑或智能手机。

On the book's website, https://latexguide.org, you can read, edit, and compile every code example in this book online without installing anything. An internet browser with JavaScript enabled is all you need for this, and a PC, laptop, tablet, or smartphone.

什么是乳胶?

What is LaTeX?

LaTeX是免费的,开放的排版文档的源码软件。换句话说,它是一个文档准备系统。LaTeX 不是文字处理器,而是一种文档标记语言。

LaTeX is free, open source software for typesetting documents. In other words, it's a document preparation system. LaTeX is not a word processor, but it's a document markup language.

它最初由 Leslie Lamport 编写,基于 Donald Knuth 的 TeX 排版引擎。人们通常将其简称为 TeX,意思是 LaTeX。它有着悠久的历史;你可以在 https://tug.org/whatis.html 上阅读它。

It was initially written by Leslie Lamport and is based on the TeX typesetting engine by Donald Knuth. People often refer to it as just TeX, meaning LaTeX. It has a long history; you can read about it at https://tug.org/whatis.html.

现在,让我们继续看看如何充分利用 LaTeX。

For now, let's continue by looking at how we can make the most of LaTeX.

乳胶的好处

Benefits of LaTeX

乳胶是特别适用于科学和技术文件。LaTeX 出众的数学公式排版堪称传奇。假设你是学生或科学家。在这种情况下,LaTeX 是迄今为止最好的选择,即使您不需要它的科学功能,也有其他用途 — 它可以产生非常高质量的输出并且非常稳定。它可以轻松处理复杂的文档,无论它们有多大。

LaTeX is especially well suited for scientific and technical documents. LaTeX's superior typesetting of mathematical formulas is legendary. Suppose you are a student or a scientist. In that case, LaTeX is by far the best choice, and even if you don't need its scientific capabilities, there are other uses—it produces very high-quality output and is incredibly stable. It handles complex documents easily, no matter how large they are.

LaTeX 的一些更显着的优势是它的交叉引用能力、自动编号能力以及目录、图形和表格、索引、词汇表和参考书目列表的生成。它是多语言的,具有特定于语言的功能,并且可以使用 PostScript 和 PDF 功能。

Some more remarkable strengths of LaTeX are its cross-referencing capabilities, the ability for automatic numbering, and the generation of lists of contents, figures and tables, indexes, glossaries, and bibliographies. It is multilingual with language-specific features, and it can use PostScript and PDF features.

除了非常适合科学家之外,LaTeX 还非常灵活——有用于信件、演示文稿、账单、哲学书籍、法律文本、乐谱,甚至国际象棋游戏符号的模板。数以百计的 LaTeX 用户为各种可能的目的编写了数以千计的模板、样式和有价值的工具。它在存档服务器上在线收集和分类。

Apart from being perfect for scientists, LaTeX is incredibly flexible—there are templates for letters, presentations, bills, philosophy books, law texts, music scores, and even chess game notation. Hundreds of LaTeX users have written thousands of templates, styles, and valuable tools for every possible purpose. It is collected and categorized online on archiving servers.

从其默认样式开始并依靠其智能格式,您可以从其令人印象深刻的高质量中受益,但您可以自由定制和修改所有内容。人们TeX 社区的一些人已经编写了很多扩展来解决几乎所有的格式化需求。

You could benefit from its impressive high quality by starting with its default styles and relying on its intelligent formatting, but you are free to customize and modify everything. People of the TeX community have already written a lot of extensions addressing nearly every formatting need.

开源的优点

Virtues of open source

代码乳胶是完全开源、免费且可供所有人阅读。这使您能够研究和改变一切,从 LaTeX 的核心到最新的扩展包。但这对初学者来说意味着什么?有一个庞大的 LaTeX 社区,有很多友好、乐于助人的人。即使您不能直接从开源代码中获益,他们也可以阅读源代码并为您提供帮助。只需加入 LaTeX 网络论坛并在那里提问。如有必要,帮助者将深入研究 LaTeX 源代码,并且很可能会为您找到解决方案,有时会推荐合适的包,通常会提供默认命令的重新定义。

The code of LaTeX is entirely open source, free, and readable for everyone. This enables you to study and change everything, from the core of LaTeX to the latest extension packages. But what does this mean for you as a beginner? There's a huge LaTeX community with a lot of friendly, helpful people. Even if you cannot benefit from the open source code directly, they can read the source and assist you. Just join a LaTeX web forum and ask your questions there. Helpers will, if necessary, dig into LaTeX sources and, in all probability, find a solution for you, sometimes by recommending a suitable package, often providing a redefinition of a default command.

今天,我们已经从 LaTeX 社区大约 30 年的发展中获益。开源理念使之成为可能,因为每个用户都被邀请研究和改进软件并进一步开发它。第 14 章使用在线资源,将指明通往社区的道路。

Today, we're already profiting from about 30 years of development by the LaTeX community. The open source philosophy made it possible, as every user is invited to study and improve the software and develop it further. Chapter 14, Using Online Resources, will point the way to the community.

形式与内容分离

Separation of form and content

一个基本的LaTeX 的原则是作者不应该因为格式问题而分心。通常,作者在逻辑上关注内容和格式。例如,不用用大而粗的字母写章节标题,您只需告诉 LaTeX 这是一个章节标题。您可以让 LaTeX 设计标题或在文档的设置中决定标题的外观——只需一次所有的文档。LaTeX 广泛使用称为包的样式文件,使设计和修改整个文档的外观及其所有细节变得容易。

A fundamental principle of LaTeX is that the author should not be distracted too much by formatting issues. Usually, the author focuses on the content and formats logically. For example, instead of writing a chapter title in big, bold letters, you just tell LaTeX that it's a chapter heading. You can let LaTeX design the heading or decide in the document's settings what the headings will look like—just once for the whole document. LaTeX extensively uses style files called classes and packages, making it easy to design and modify the entire document's appearance and all of its details.

可移植性

Portability

乳胶是适用于几乎所有操作系统,例如 Windows、Linux、Mac OS X 等等。它的文件格式是纯文本,在所有操作系统上都是可读和可编辑的,这意味着 LaTeX 将在每个系统上产生相同的输出。有几种 LaTeX 软件包,我们称之为TeX 发行版。我们将专注于TeX Live发行版,因为它适用于 Windows、Linux 和 Mac OS X。在 Mac 上,原生 TeX Live 版本是称为MacTeX

LaTeX is available for nearly every operating system, such as Windows, Linux, Mac OS X, and many more. Its file format is plain text, readable and editable on all operating systems, which means LaTeX will produce the same output on each system. There are several LaTeX software packages, which we call TeX distributions. We will focus on the TeX Live distribution since this one is available for Windows, Linux, and Mac OS X. On the Mac, the native TeX Live version is called MacTeX.

LaTeX 没有图形用户界面;这就是它如此便携的原因之一。您可以选择任何文本编辑器。每个操作系统都有许多编辑器,甚至专门研究 LaTeX。一些编辑器可用于多个系统;例如,TeXworks运行在 Windows、Linux 和 Mac OS X 上,这是我们将在本书中使用它的原因之一。另一个重要原因是它可能最适合初学者。

LaTeX doesn't have a graphical user interface; that's one of the reasons why it's so portable. You can choose any text editor. There are many editors, even specialized in LaTeX, for every operating system. Some editors are available for several systems; for instance, TeXworks runs on Windows, Linux, and Mac OS X, which is one of the reasons why we will use it in our book. Another significant reason is that it's probably best suited for beginners.

LaTeX 生成 PDF 输出,它在大多数计算机上都是可打印和可读的,并且无论操作系统如何,它看起来都一样。除 PDF 外,它还支持 DVI、PostScript 和 HTML 输出,为印刷和在线分发奠定了基础,例如在个人计算机、电子书阅读器和智能手机上。总而言之,LaTeX 在三个方面是可移植的:您的源代码、实现和输出。

LaTeX generates PDF output, which is printable and readable on most computers and looks identical regardless of the operating system. Besides PDF, it supports DVI, PostScript, and HTML output, preparing the ground for distribution both in print and online, such as on personal computers, electronic book readers, and smartphones. To sum up, LaTeX is portable in three ways: your source, implementation, and output.

保护您的工作

Protection for your work

乳胶文档以人类可读的文本格式存储,而不是以某种晦涩的专有文字处理格式存储,这种格式可能会在同一软件的不同版本中发生变化。

LaTeX documents are stored in human-readable text format, not in some obscure proprietary word processing format, that may be altered in a different version of the same software.

尝试打开一份用商用文字处理器编写的 20 年前的文档。您的现代软件会显示什么?即使您可以读取该文件,它的视觉外观也无疑会与以前不同。LaTeX 承诺文档始终是可读的,并且会产生相同的输出。即使它得到进一步发展,它仍将保持向后兼容。

Try to open a 20-year-old document written with a commercial word processor. What might your modern software show? Even if you can read the file, its visual appearance would undoubtedly be different than before. LaTeX promises that the document will always be readable and will result in the same output. Even though it's further developed, it will remain backward compatible.

文字处理器文档可能会感染病毒,恶意宏可能会破坏数据。您听说过“隐藏”在文本文件中的病毒吗?LaTeX 文档不受病毒威胁。

Word processor documents could be infected with viruses, and malicious macros could destroy the data. Did you ever hear of a virus "hiding" in a text file? LaTeX documents are not threatened by viruses.

如何开始使用 LaTeX

How to get started with LaTeX

学习中曲线可能很陡峭,但这本书将帮助您掌握它。

The learning curve could be steep, but this book will help you master it.

虽然编写 LaTeX 看起来像编程,但不要害怕。很快您就会知道常用的命令,而具有自动完成和关键字突出显示功能的文本编辑器将为您提供支持。他们甚至可能会为您提供带有命令的菜单和对话框。

Though writing LaTeX looks like programming, don't be afraid. Soon you will know the frequently used commands, while text editors with auto-completion and keyword highlighting will support you. They might even provide menus and dialogs with commands for you.

您是否仍然认为需要很长时间才能通过学习取得令人信服的成绩?不用担心; 这本书会给你一个快速的开始。您将通过大量示例练习来学习。可以从互联网上阅读和下载更多示例。在第 14 章使用在线资源,我们将探索在线资源。有 LaTeX 帮助论坛,您可以在其中获得问题的答案。具体来说,https://latex.org 有一个专门为本书读者提供的论坛。去那里拜访我们!

Do you still think it will take a long time until you can learn to achieve creditable results? Don't worry; this book will give you a quick start. You will learn by practicing with a lot of examples. Many more examples can be read and downloaded from the internet. In Chapter 14, Using Online Resources, we will explore online resources. There are LaTeX help forums where you get answers to your questions. Specifically, https://latex.org has a forum dedicated to the readers of this book. Visit us there!

使用 LaTeX 的方法

Approaches to working with LaTeX

使用 LaTeX 的两种方法:

There are two ways to approach working with LaTeX:

  • 传统的方式是在自己的电脑上安装 LaTeX。它非常简单,我们将在安装和使用 LaTeX部分介绍在 Windows 上的安装。
  • The traditional way is to install LaTeX on your own computer. It's pretty straightforward, and we will walk through installing on Windows in the Installing and using LaTeX section.
  • 另一种方法是在云端使用在线 LaTeX 。无需安装;您只需要一台联网的电脑、平板电脑或手机。我们将在本章末尾的使用 Overleaf 在线使用 LaTeX部分探讨此选项。
  • Another way is to use LaTeX online in the cloud. No installation is needed; all you need is an internet-connected computer, tablet, or phone. We will explore this option in the Working with LaTeX online using Overleaf section at the end of this chapter.

现在,我们将继续在我们的计算机上设置 LaTeX。如果你愿意,你可以暂时跳过它并跳到使用背页在线使用 LaTeX部分,然后决定你想采用哪种方法。

Now, we will continue with the setup of LaTeX on our computer. If you like, you could skip it for the moment and jump to the Working with LaTeX online using Overleaf section, and then decide which approach you would like to take.

安装和使用 LaTeX

Installing and using LaTeX

开始吧安装 LaTeX 发行版TeX Live。这发行版适用于 Windows、Linux、Mac OS X ( MacTeX ) 和其他类 Unix 操作系统。TeX Live 得到了很好的维护,并且得到了积极的开发。

Let's start with the installation of the LaTeX distribution, TeX Live. This distribution is available for Windows, Linux, Mac OS X (MacTeX), and other Unix-like operating systems. TeX Live is well maintained, and it is actively developed.

替代 LaTeX 分布

Alternative LaTeX distribution

另一个适用于 Windows 的优秀且用户友好的 LaTeX 发行版是MiKTeX。它很容易安装,就像任何其他 Windows 应用程序。您可以从 https://miktex.org 下载它。访问 https://latexguide.org/distributions 以获得详细的最新比较。

Another excellent and user-friendly LaTeX distribution for Windows is MiKTeX. It's easy to install, like any other Windows application. You can download it from https://miktex.org. Visit https://latexguide.org/distributions for a detailed, up-to-date comparison.

您可以为单个用户(就是您)安装 TeX Live,也可以为计算机上的所有用户共享安装。后者是称为管理模式。它需要以管理员身份运行安装:使用管理员帐户登录或右键单击安装程序并选择Run as administrator

You can install TeX Live for a single user (that's you) or as a shared installation for all users on a computer. The latter is called admin mode. It requires running the installation as an administrator: either log in with an administrator account or right-click on the install program and choose Run as administrator.

建议以单用户模式安装。

It is recommended to install in single-user mode.

首先,我们将访问 TeX Live 主页并对安装可能性进行调查。为此,请使用https://tug.org/texlive/打开 TeX Live 主页:

First, we will visit the TeX Live homepage and take a survey of the installation possibilities. To do this, open the TeX Live homepage using https://tug.org/texlive/:

图 1.1 – TeX Live 主页

图 1.1 – TeX Live 主页

Figure 1.1 – TeX Live home page

随意深入探索主页以研究那里提供的信息,不过,在本书中,我们将介绍两种安装类型:

Feel free to explore the home page in depth to study the information offered there, though, in this book, we will cover two types of installation:

  • 使用网络安装向导安装 TeX Living;这将是在线的,需要互联网连接。
  • Installing TeX Living using the net installer wizard; this will be online and requires an internet connection.
  • 离线安装 TeX;首先需要大量下载,然后我们可以离线进行。
  • Installing TeX offline; this starts with a considerable download, but then we can do it offline.

在开始安装之前,我们先看一下不同粒度的LaTeX打包约定:

Before we start the installation, let's have a look at LaTeX packaging conventions with different granularity:

  • 一个,还有称为样式文件,是一个带有一些宏的单个 LaTeX 文件,用于添加特定功能或提供特定外观和文档样式。它的文件扩展名为.sty
  • A package, also called a style file, is a single LaTeX file with some macros to add specific features or provide a particular look and document style. It has the filename extension .sty.
  • 捆绑是一组具有相似目的的包。它还可能包含文件扩展名为.cls的类文件。
  • A bundle is a set of packages with a similar purpose. It may also contain class files that have the filename extension .cls.
  • 集合是针对某个感兴趣领域一组更大的包。例如,这可以是一组广泛的数学和自然科学包、音乐包或与图形相关的包。
  • A collection is a larger set of packages for a field of interest. That can be, for example, an extensive set of math and natural science packages, music packages, or graphics-related packages.
  • 方案是特定大小LaTeX 安装。这可以是最小的(能够工作的最小的)、基本的(通常需要的东西)或完整的(所有可用的东西)。
  • A scheme is a LaTeX installation of a specific size. That can be minimal (the smallest to be able to work), basic (commonly needed stuff), or full (everything available).

了解了这些知识后,我们现在就可以安装和更新 LaTeX。最简单的选择是完全安装所有内容,即完整方案。这样,您就不会错过任何包裹。

We can now install and update LaTeX with this understanding. The easiest option is to install everything fully, that is, the full scheme. That way, you will not miss any packages.

让我们看看在 Windows PC 上的两种安装方法。第一个将是安装通过互联网,这需要良好的互联网连接。如果你没有良好的互联网连接,请转到下一节,离线安装 TeX Live

Let's check out two installation methods on a Windows PC. The first one will be installing over the internet, which requires a good internet connection. If you don't have a good internet connection, go to the next section, Installing TeX Live offline.

使用网络安装程序向导安装 TeX Live

Installing TeX Live using the net installer wizard

我们将要下载 TeX Live 网络安装程序并在我们的计算机上安装完整的 TeX Live 发行版。为此,请按照下列步骤操作:

We will download the TeX Live net installer and install the complete TeX Live distribution on our computer. To do this, follow these steps:

  1. 如图 1.1所示点击下载,或者访问https://tug.org/texlive/acquire-netinstall.html

    图 1.2 – 安装说明

    图 1.2 – 安装说明

  2. Click on download as seen in Figure 1.1, or go to https://tug.org/texlive/acquire-netinstall.html:

    Figure 1.2 – Installation instructions

  3. 下载可执行安装程序程序,安装-tl-windows.exe,然后运行该程序。
  4. Download the executable installer program, install-tl-windows.exe, and run the program.
  5. 确认安装模式(作为单用户或管理员,点击下一步,然后点击安装
  6. Confirm the installation mode (as a Single-user or as the Administrator), click Next, and then Install.
  7. 网络安装程序会自动检测您的操作系统语言。你可以改变通过在打开的窗口的菜单中单击GUI 语言来选择图形用户界面( GUI )的语言,如图1.3所示:
    图 1.3 – TeX Live 安装程序

    图 1.3 – TeX Live 安装程序

  8. The net installer will automatically detect your operating system language. You can change the language of the Graphical User Interface (GUI) by clicking on GUI language in the menu of the window that opens, as we can see in Figure 1.3:

    Figure 1.3 – TeX Live Installer

  9. 更改安装根目录,即硬盘上所有 TeX Live 安装文件的位置。完整的默认安装很好,但您可以单击“高级”以确定更具体的情况,如您在此处看到的:
    图 1.4 – TeX Live Installer 高级选项

    图 1.4 – TeX Live Installer 高级选项

  10. You can change the installation root, that is, the location of all TeX Live installed files on your hard drive. That complete default installation is fine, though you can click on Advanced to determine what shall happen more specifically, as you can see here:

    Figure 1.4 – TeX Live Installer advanced options

  11. 更改方案(选项包括FullMediumSmall)并自定义软件集合的数量,例如安装的格式、字体、样式、图形包、编辑器、语言支持等等。由于推荐的选项已经是安装中最重要的部分,取消选中某些集合不会节省太多空间。推荐完整方案。
  12. You can change the Scheme (options include Full, Medium, and Small) and customize the number of software collections, such as installed formats, fonts, styles, graphics packages, editor, language support, and many more. As the recommended options are already the most significant parts of the installation, unchecking some collections won't save much space. The full scheme is recommended.
  13. 单击安装继续。现在,很长一段时间不需要交互,您可以在下载并安装所有数千个 TeX 包的同时向后靠:
    图 1.5 – 安装进度

    图 1.5 – 安装进度

  14. Click on Install to proceed. Now, there's no interaction needed for a long time, and you can lean back while all the thousands of TeX packages are downloaded and installed:

    Figure 1.5 – Installation progress

  15. 最后,你会受到欢迎信息。单击Close完成。
  16. Finally, you will get a welcome message. Finish by clicking on Close.

您已经完成了 TeX Live 的安装。现在您的开始菜单包含一个包含六个程序的TeX Live 2021文件夹:

You have completed the installation of TeX Live. Now your Start menu contains a TeX Live 2021 folder containing six programs:

图 1.6 – Windows 开始菜单中的 TeX Live

图 1.6 – TeX住在 Windows 开始菜单中

Figure 1.6 – TeX Live in the Windows Start menu

让我们简要地看一下每个程序:

Let's briefly look at each of the programs:

  • DVIOUT DVI 查看器— 经典 LaTeX 输出格式 DVI 的查看器程序(如今,大多数人选择 PDF 输出,因此您可能不需要这个)。
  • DVIOUT DVI viewer—a viewer program for the classic LaTeX output format DVI (today, most people choose PDF output, so you probably won't need this).
  • TeX Live 命令行——如果您想在命令行运行其他 TeX live 程序,请使用它。
  • TeX Live command-line—use this if you would like to run other TeX live programs at the command line.
  • TeX Live 文档— 在您的网络浏览器中打开 TeX Live 手册。
  • TeX Live documentation—opens the TeX Live manual in your web browser.
  • TeX Live Manager — 这是您的包管理工具(例如,用于安装和更新 LaTeX 包)。
  • TeX Live Manager—this is your tool for package management (for example, for installing and updating LaTeX packages).
  • TeXworks 编辑器——这是一款专为轻松创建 LaTeX 文档而开发的编辑器。我们将在本书中大量使用 TeXworks。
  • TeXworks editor—this is an editor that was developed to create LaTeX documents comfortably. We will make extensive use of TeXworks in this book.
  • 卸载 TeX Live——使用这个你从头开始安装一个新的 TeX Live 版本,或者你想安装 MiKTeX。
  • Uninstall TeX Live—use this before you install a new TeX Live version from scratch, or if you would like to install MiKTeX instead.

现在我们将完成 TeX Live 的离线安装。

Now we will go through the offline installation of TeX Live.

离线安装 TeX Live

Installing TeX Live offline

每年,TeX 用户组创建了一个 TeX 软件集 DVD 并将其发送给他们的成员。您可以从 TUG 会员处获得 DVD 或从 TUG 网上商店购买,2021 年 DVD 的售价为 16 美元。但我们可以免费下载 DVD 的内容。

Every year, the TeX user group creates a TeX software collection DVD and sends it to their members. You can get a DVD from a TUG member or purchase it from the TUG web store, where it's listed for $16 in 2021. But we can download the DVD's content for free.

我们现在将下载一个大小约为 4 GB 的 TeX Live ISO 映像。提取后,我们可以将其刻录到 DVD 上并从那里运行安装。为此,请按照下列步骤操作:

We will now download an ISO image of TeX Live with a size of about 4 GB. After extraction, we can burn it on a DVD and run the installation from there. To do this, follow these steps:

  1. 访问https://tug.org/texlive/acquire-iso.html上的下载区。
  2. Visit the download area at https://tug.org/texlive/acquire-iso.html.
  3. 下载texlive.iso文件。如果可能,请使用下载管理器,尤其是在您的互联网连接不稳定的情况下。
  4. Download the texlive.iso file. If possible, use a download manager, especially if your internet connection is not stable.
  5. 使用支持 ISO 格式的刻录软件将 ISO 文件刻录到 DVD 上,或者将其解压缩到硬盘驱动器。例如,免费程序7-zip可以提取 ISO 文件。
  6. Either burn the ISO file on a DVD using burning software that supports the ISO format, or extract it to your hard disk drive. For example, the free program 7-zip can extract ISO files.
  7. 在提取的文件或 DVD 上,您会找到安装程序批处理文件install-tlinstall-tl-advanced。选择一个,启动它,然后进行类似于在线安装的安装。有关更多信息,请访问 https://tug.org/texlive/quickinstall.html。
  8. Among the extracted files or on your DVD, you will find the installer batch files install-tl and install-tl-advanced. Choose one, start it, and go through the installation similar to the online installation. More information is available on https://tug.org/texlive/quickinstall.html.

离线安装 TeX 就像第一次安装一样。尽管如此,这次您已经获得了所有数据,并且在安装过程中或进行其他安装时不需要互联网连接。如果可以预见您稍后会在另一台计算机上安装 TeX Live,或者如果您想将其送给朋友或同事。

Installing TeX offline was just like the first installation. Still, this time you've got all the data, and you won't need an internet connection during the installation or for another installation. This download approach is especially recommended if it's foreseeable that you will install TeX Live on another computer later, or if you would like to give it to friends or colleagues.

由于 TeX 也可以在其他操作系统上运行,因此让我们简要了解一下其他系统。

As TeX runs on other operating systems as well, let's take a brief look at other systems.

在其他操作系统上安装 TeX Live

Installing TeX Live on other operating systems

TeX 也在 Windows 以外的许多系统上。快速浏览一下:

TeX also runs on a lot of systems other than Windows. Here's a quick glance:

  • Mac OS X :您可以在https://tug.org/mactex/下载自定义版本的 TeX Live 。下载巨大的.pkg文件并双击它进行安装。它将打印非常简单的说明。
  • Mac OS X: You can download a customized version of TeX Live at https://tug.org/mactex/. Download the huge .pkg file and double-click on it to install. It will print very straightforward instructions.
  • Ubuntu Linux:使用软件中心安装 TeX Live 包,或运行sudo apt-get install texlive-full来获取所有内容。
  • Ubuntu Linux: Use the Software Center to install TeX Live packages, or run sudo apt-get install texlive-full to get everything.
  • Debian Linux:使用Synaptic安装 TeX Live 软件包,或运行apt-get install texlive-full(通过sudo或以 root 用户身份)来获取所有内容。
  • Debian Linux: Use Synaptic to install TeX Live packages, or run apt-get install texlive-full (via sudo or as root user) to get everything.
  • Red Hat、CentOS 和 Fedora Linux:使用Red Hat 包管理器,或通过命令提示符使用yum,例如yum install texlive-scheme-full,或 DNF:sudo dnf install texlive-scheme-full
  • Red Hat, CentOS, and Fedora Linux: Use the Red Hat package manager, or yum via Command Prompt, such as yum install texlive-scheme-full, or DNF: sudo dnf install texlive-scheme-full.
  • 其他:访问https://tug.org/texlive/quickinstall.html并按照说明进行操作。
  • Others: Visit https://tug.org/texlive/quickinstall.html and follow the instructions.

如果您想保持优势,您可以从其主页下载并安装最新版本的 TeX Live,而不是从操作系统的存储库中下载并安装最新版本,如最后一点所述。

If you want to stay on the edge, you could download and install the most current version of TeX Live from its home page instead of the version from the operating system's repositories, as mentioned in the last point.

要是我们需要更新或添加包,以下部分将向您展示如何操作。

If we need to update or add packages, the following section shows you how.

更新 TeX Live 并安装新包

Updating TeX Live and installing new packages

LaTeX 开发人员更新它不断地更新,包括新功能和错误修复。您可以不时更新您的系统。

The LaTeX developers update it continuously, both for new features and for bug fixes. From time to time, you can update your system.

为此,转到开始菜单,然后是TeX Live文件夹,然后启动TeX Live Manager(也提到的简称为tlmgr,也称为TeX Live Shell)。此应用程序用于更新和安装附加包。看看这个截图,这样我们就可以讨论如何使用 TeX Live Manager:

To do this, go to the Start menu, then the TeX Live folder, and start the TeX Live Manager (also referred to as tlmgr for short, and also called TeX Live Shell). This application is both for updating and installing additional packages. Take a look at this screenshot so we can talk about how to use the TeX Live Manager:

图 1.7 – TeX Live 管理器

图 1.7 – TeX Live 管理器

Figure 1.7 – The TeX Live Manager

第一部分在 TeX Live 管理器中显示存储库。存储库是带有 TeX Live 软件存档的服务器。如果您所在地区的默认存储库不可用或速度太慢,您可以单击“选项”从列表中选择另一个存储库。

The first section in the TeX Live Manager shows the Repository. A repository is a server with a TeX Live software archive. If the default repository is unavailable or is too slow in your area, you can click on Options to choose another repository from a list.

单击文件| 加载存储库以将 LaTeX 与最新的软件状态同步。

Click on File | Load repository to synchronize LaTeX with the latest software status.

PACKAGE LIST部分,您可以按名称搜索包或过滤视图以查看所有可用包或仅查看已安装、未安装或可更新的包。在图 1.7的中间,您可以看到一个更改粒度的选项,以查看所有包或仅查看集合或方案。

In the PACKAGE LIST section, you can search packages by name or filter the view to see all available packages or only those installed, not installed, or updatable. In the middle of Figure 1.7, you can see an option to change the granularity to see all the packages or only collections or schemes.

最下面的部分显示了选择过滤器时的包,以及简短的描述和版本。您可以在这里选择套餐。如果您想安装选定的软件包,则可以单击安装标记,或者单击删除标记以卸载它们。

The lowest section shows the packages when a filter is selected, with a short description and the version. You can choose packages here. Then you can click on Install marked if you would like to install the selected packages or click on Remove marked to uninstall them.

一个简单的方法就是点击Update all。如果更新 tlmgr按钮是已启用且可点击,则有可用的 TeX Live Manager 更新,您可以点击更新 tlmgr按钮进行更新。

An easy way is just to click on Update all. If the Update tlmgr button is enabled and clickable, then there's a TeX Live Manager update available, and you can click the Update tlmgr button to update.

每年更新

Yearly updates

更新过程仅适用于相同的 TeX Live 版本。每年,都会有一个新的 TeX Live 版本以年份作为版本号。最好卸载当前的 TeX Live 进行年度升级,然后从头开始安装新版本。在https://tug.org/texlive/上,您可以看到带有预计日期的升级计划。

The update procedure is only for the same TeX Live version. Every year, there's a new TeX Live version with the year as the version number. It would be best to uninstall the current TeX Live for a yearly upgrade and then install the new version from scratch. On https://tug.org/texlive/, you can see the upgrade plan with estimated dates.

现在我们已经准备好了基础,让我们开始编写 LaTeX 吧!

Now that we've prepared the ground, let's start to write LaTeX!

创建我们的第一个文件

Creating our first document

我们已经安装TeX 和编辑器;现在,让我们开始深入研究,使用 TeXworks 编辑器编写我们的第一个 LaTeX 文档。

We've installed TeX and an editor; now, let's jump in at the deep end by writing our first LaTeX document using the TeXworks editor.

对于 Mac 用户

For Mac users

当您在这里看到Ctrl键时,请使用Cmd键。

Please use the Cmd key when you see the Ctrl key here.

我们的第一个目标是创建一个只打印一个句子的文档。我们想用它来了解 LaTeX 文档的基本结构。为此,请按照下列步骤操作:

Our first goal is to create a document that prints out just one sentence. We want to use it to understand the basic structure of a LaTeX document. To do this, follow these steps:

  1. 通过单击桌面图标或在“开始”菜单中打开它来启动 TeXworks 编辑器。在图 1.8中,您可以看到带有菜单、按钮和工具栏的编辑器。
  2. Launch the TeXworks editor by clicking on the desktop icon or by opening it in the Start menu. In Figure 1.8, you can see the editor with the menu, buttons, and toolbar.
  3. 单击新建按钮(或键入Ctrl + N)或选择文件| 菜单中的新功能。
  4. Click on the New button (or type Ctrl + N) or choose File | New in the menu.
  5. 输入以下行:

    \文档类{文章}

    \开始{文档}

    这是我们的第一份文件。

    \end{文档}

  6. Enter the following lines:

    \documentclass{article}

    \begin{document}

    This is our first document.

    \end{document}

  7. 点击单击“保存”按钮(或键入Ctrl + S)以保存文档。选择您要存储 LaTeX 文档的位置,最好是在它自己的文件夹中。
  8. Click on the Save button (or type Ctrl + S) to save the document. Choose a location where you want to store your LaTeX documents, ideally in its own folder.
  9. 确保在 TeXworks 工具栏的下拉字段中选择了pdfLaTeX (无论如何这应该是默认值):

    图 1.8 – TeXworks 编辑器

    图 1.8 – TeXworks 编辑器

  10. Make sure that in the drop-down field in the TeXworks toolbar, pdfLaTeX is selected (this should be the default anyway):

    Figure 1.8 – The TeXworks editor

  11. 单击排版按钮或按Ctrl + T。
  12. Click the Typeset button or press Ctrl + T.
  13. 输出窗口将自动打开。看看它:
  14. The output window will automatically open. Have a look at it:

图 1.9 – TeXworks 编辑器中的 PDF 输出

图 1.9 – TeXworks 编辑器中的 PDF 输出

Figure 1.9 – The PDF output in the TeXworks editor

那是 LaTeX 文档生命周期的最初几分钟。您可以对其进行编辑、排版和检查输出,然后再次编辑。不要忘记经常保存文档。

Those were the first few minutes of the life of a LaTeX document. You may edit it, typeset and check the output, and edit again. Don't forget to save your document frequently.

如上所述较早前,与经典的文字处理软件相比,您无法立即看到更改的效果——但只需单击一下即可获得结果。

As mentioned earlier, in contrast to the classic word processor software, you cannot see the effect of changes immediately—but the result is just one click away.

检查高级 LaTeX 编辑器

Checking out advanced LaTeX editors

你有有处理复杂程序的经验吗?您喜欢使用功能丰富且功能强大的编辑器吗?然后看看这些 LaTeX 编辑器。访问他们的网站以查找屏幕截图并了解其功能:

Do you have experience in working with complex programs? Do you like using a feature-rich and powerful editor? Then have a look at these LaTeX editors. Visit their websites to find screenshots and to read about their features:

这些编辑器是免费的开源软件。您可以在https://latexguide.org/editors找到更多信息。

These editors are free, open source software. You can find more at https://latexguide.org/editors.

在线编辑器可在任何支持互联网的操作系统上运行。让我们仔细看看在线下一节中的编辑器和编译器。

Online editors run on any internet-capable operating system. Let's take a close look at an online editor and compiler in the following section.

使用 Overleaf 在线使用 LaTeX

Working with LaTeX online using Overleaf

安装中乳胶建议在您的计算机上安装它,但它可能会占用您的硬盘驱动器大约 8 GB 的空间,并且需要两个小时来安装它。

Installing LaTeX on your computer is recommended, but it can take up about 8 GB on your hard drive and two hours to install it.

在您的互联网浏览器中简单地使用 LaTeX 怎么样?Overleaf来了。它是热衷于 TeX 的数学家于 2011 年发起的纯在线 LaTeX 服务。您可以通过此链接访问它: https: //www.overleaf.com

How about simply using LaTeX in your internet browser? Here comes Overleaf. It's a pure online LaTeX service that mathematicians enthusiastic about TeX started in 2011. You can access it through this link: https://www.overleaf.com.

在关于 Overleaf 的这一节中,我们将执行以下操作:

In this section about Overleaf, we will do the following:

  • 检查背页要求
  • Check the Overleaf requirements
  • 看看Overleaf的好处
  • Look at the benefits of Overleaf
  • 评估可能的注意事项
  • Evaluate possible caveats
  • 使用背页编辑器
  • Use the Overleaf editor
  • 试用 Writefull
  • Try out Writefull

我们现在上网吧。

Let's go online now.

Overleaf 要求和交付的内容

What Overleaf requires and delivers

使用在背面,您需要以下内容:

To use Overleaf, you need the following:

  • 任何互联网浏览器,例如 Firefox、Chrome、Opera 或 Edge。
  • Any internet browser, such as Firefox, Chrome, Opera, or Edge.
  • 您不需要任何其他本地软件,例如 LaTeX 编译器、编辑器或 PDF 查看器。
  • You don't need any other local software such as a LaTeX compiler, editor, or PDF viewer.

它的基本用法是免费的,涵盖了很多内容。它提供了一个完整的 TeX Live,具有无限的项目和功能丰富的编辑器,与另一个用户的实时同步协作,以及数百个模板。您可以免费使用 Overleaf 轻松撰写论文或书籍。

It is free for basic usage, and that covers a lot. It provides a complete TeX Live with unlimited projects and a feature-rich editor, real-time-sync collaboration with another user, and hundreds of templates to start with. You can easily write your thesis or book with Overleaf with free usage.

高级个人或专业订阅需要付费并提供额外的功能,例如:

An advanced personal or professional subscription costs money and provides additional features, such as the following:

  • 每个项目的合作者数量不受限制
  • Unlimited collaborators per project
  • 文档历史记录(在文档版本之间来回切换)
  • Document history (going back and forth between document versions)
  • 高级书目管理(使用 Mendeley)
  • Advanced bibliography management (with Mendeley)
  • Dropbox 同步整合
  • Dropbox sync integration
  • GitHub 整合
  • GitHub integration
  • 优先个人支持
  • Priority personal support

先进的功能超越了普通的 LaTeX。您可以检查您是否符合条件;许多大学和机构与 Overleaf 合作,为其成员提供全面服务。

The advanced features go beyond regular LaTeX. You can check if you are eligible; many universities and institutions partner with Overleaf to provide their members the full service.

背页的好处

Benefits of Overleaf

让我们看看与在计算机上本地使用经典编辑器相比,使用 Overleaf 可以获得什么。使用 Overleaf,您可以执行以下操作:

Let's look at what you can gain when using Overleaf, compared to using classic editors locally on your computer. With Overleaf, you can do the following:

  • 在任何设备上使用它,例如 PC、笔记本电脑、平板电脑或智能手机。
  • Use it on any device, such as a PC, laptop, tablet, or smartphone.
  • 在无法自行安装任何东西的锁定工作计算机上使用它。
  • Use it on a locked-in work computer where you cannot install anything yourself.
  • 使用密码登录后,可以在任何设备(私人或工作或图书馆计算机)上访问您自己的文件。
  • Access your own files on any device (be it a private or work or library computer) once you log in with your password.
  • 如果您邀请某人与您一起工作,你们两个都可以立即编辑并查看彼此的更改,从而使协作变得容易。
  • If you invite somebody to work with you, both of you can instantly edit and see each other's changes, making collaboration easy.
  • 在您键入时自动实时查看 PDF 结果。
  • Have an automatic real-time view of the PDF result while you type.
  • 访问 LaTeX 项目的版本历史记录以跟踪更改。
  • Access a version history for LaTeX projects to track changes.
  • 用注释和答案对 LaTeX 源代码进行注释。
  • Annotate LaTeX source code with comments and answers to them.
  • 无需升级即可使用新的 LaTeX 软件。
  • Work with a new LaTeX software without doing an upgrade.

然而,有Overleaf 面临一些挑战。让我们现在考虑一下。

However, there are some challenges to Overleaf. Let's think about that now.

在线工作的注意事项

Caveats of working online

成为清楚,可能有一些警告:

To be clear, there can be some caveats:

  • 您始终需要可用的互联网。
  • You always need the internet available.
  • 由于您的文档在线存储,因此您必须依靠 Overleaf 的数据安全和隐私。请参阅https://www.overleaf.com/legal
  • As your documents are stored online, you have to rely on data security and privacy by Overleaf. See https://www.overleaf.com/legal.
  • 您依赖 Overleaf 的功能;在更新之前,他们的 TeX 版本可能会落后于官方 TeX Live。
  • You depend on Overleaf's features; their TeX version could be a bit behind the official TeX Live until they update theirs.
  • 速度取决于他们的服务器和您的网络连接,而不仅仅是您自己计算机的性能。
  • The speed depends on their servers and your network connection, not just on your own computer's performance.

让我们仔细看看 Overleaf 是如何工作的。

Let's take a closer look at how Overleaf works.

在线创建我们的第一个文档

Creating our first document online

我们想分两步在 Overleaf 上创建我们自己的空间。然后我们将开始我们的第一个 LaTeX 项目:

We want to create our own space on Overleaf in two steps. Then we will start our first LaTeX project:

  1. 注册服务。单击Overleaf 主页上的“注册”或转到https://www.overleaf.com/register。输入您的电子邮件地址并选择一个密码。
  2. Register for the service. Either click on Register on the Overleaf home page or go to https://www.overleaf.com/register. Enter your email address and choose a password.
  3. 登录背页。单击首页上的登录或转到https://www.overleaf.com/login
    图 1.10 – 创建一个新项目

    图 1.10 – 创建一个新项目

    为什么我们需要注册?

    可以到达通过电子邮件地址基本上是为了遵守数据保护法。如果您忘记了密码,您可以要求 Overleaf 将密码重置链接发送到您的电子邮件地址。一般来说,通过使用您的电子邮件地址,您可以在需要时证明您的身份和数据所有权。

  4. Log in to Overleaf. Either click on Login on the front page or go to https://www.overleaf.com/login:

    Figure 1.10 – Creating a new project

    Why do we need to register?

    To be reachable via an email address is basically to comply with data protection law. If you forget your password, you can ask Overleaf to send a password reset link to your email address. In general, by using your email address, you can prove your identity and ownership of your data if you ever need to.

  5. 单击新建项目按钮。将出现一个下拉列表,您可以在其中选择一个空白项目或一个基于模板的项目,例如书籍、演示文稿、简历或论文模板。现在,我们只选择Blank Project
  6. Click the New Project button. A drop-down list will appear, where you can choose to have a blank project or one based on a template, such as a book, presentation, CV, or thesis template. For now, we just choose Blank Project.
  7. Overleaf 要求您提供姓名;选一个。就是这样!这就是你现在拥有的:
  8. Overleaf asks you for a name; choose one. That's it! This is what you have now:
图 1.11 – 一个新项目

图 1.11 – 一个新项目

Figure 1.11 – A new project

它不是完全空白,因为它包含一个小代码框,因此您可以快速入门,然后可以开始填写文本。

It's not entirely blank as it contains a small code frame, so you got a quick start, and you can begin filling in your text.

每当您单击Recompile按钮或按Ctrl + Enter时,右侧的预览将被刷新。打开Recompile菜单,在下拉菜单中选择Auto Compile ,即可启用自动排版功能,如图1.12所示。该文档会在您访问时频繁自动刷新打字:

Whenever you click the Recompile button or press Ctrl + Enter, the preview on the right side will be refreshed. You can enable automatic typesetting if you open the Recompile menu and choose Auto Compile in the drop-down menu, which is switched on in Figure 1.12. The document refreshes frequently and automatically while you are typing:

图 1.12 – 编译设置

图 1.12 – 编译设置

Figure 1.12 – Compiling settings

由于 Overleaf 与经典的 LaTeX 编辑器如此不同,让我们仔细看看它。

Since Overleaf is so different from classic LaTeX editors, let's have a closer look at it.

探索背页

Exploring Overleaf

快速查看操作中更复杂的文档并了解您对 Overleaf 的期望,让我们从https://www.latextemplates.com/template/masters-doctoral-thesis打开硕士/博士论文模板。到达那里后,只需单击“在背面打开”按钮。然后 Overleaf 为你创建一个项目:

To quickly see a more complex document in action and to understand what you can expect from Overleaf, let's open the Masters/Doctoral Thesis template from https://www.latextemplates.com/template/masters-doctoral-thesis. Once you are there, simply click the Open in Overleaf button. Then Overleaf creates a project for you:

图 1.13 – Overleaf 编辑器中的论文模板

图 1.13 – Overleaf 编辑器中的论文模板

Figure 1.13 – A thesis template in the Overleaf editor

图 1.13中,在最左边,你可以看到你的文件夹结构和文件。旁边是 LaTeX 源代码。在右侧,您可以在 PDF 预览中看到输出。

In Figure 1.13, on the very left, you can see your folder structure and files. Next to it, there is the LaTeX source code. On the right, you can see the output in a PDF preview.

在最基本的形式中,您在左侧编写代码,单击“重新编译”按钮,然后在右侧查看结果,就像我们之前在示例中所做的那样。

In its most basic form, you write your code on the left, click the Recompile button, and see the result on the right, as we previously did in our example.

在您工作时,Overleaf 会跟踪历史记录。您可以标记版本以便稍后检查它们。单击顶部的“历史记录”按钮会显示版本:

While you are working, Overleaf keeps track of the history. You can label versions to check them later. Clicking on the History button at the top shows you the versions:

图 1.14 – Overleaf 中的文档历史记录

图 1.14 – Overleaf 中的文档历史记录

Figure 1.14 – Document history in Overleaf

单击一个版本在右边切换到它。

Click a version on the right to switch to it.

无需查看太多屏幕截图,如果单击左上角的“菜单”按钮,您可以执行以下操作:

Without looking at too many screenshots, this is what you can do if you click on the Menu button in the top-left corner:

  • 让 Overleaf 统计您文档中的字数,不包括命令和环境等代码语法
  • Let Overleaf count the words in your document, excluding code syntax such as commands and environments
  • 与 Dropbox 或 GitHub 同步
  • Synchronize with Dropbox or GitHub
  • 选择编译器(pdfLaTeX, classic LaTeX, XeLaTeX, LuaLaTeX, for advanced users)
  • Choose the compiler (pdfLaTeX, classic LaTeX, XeLaTeX, LuaLaTeX, for advanced users)
  • 如果要使用旧的 TeX Live 版本编译旧文件或切换到较新的版本,请设置 TeX Live 版本
  • Set a TeX Live version if you want to compile an old file with an old TeX Live version or switch to a newer one
  • 如果您的项目包含多个文档,请选择一个主.tex文档
  • Select a main .tex document if your project consists of several documents
  • 为代码标记和背景选择视觉样式编辑器主题,在浅色、柔和色、深色和其他颜色之间更改颜色
  • Choose a visual style editor theme for the code markup and background, changing colors between light, pastel, dark, and others
  • 选择编辑器字体(例如 Consolas 或 Lucida)和字体大小
  • Choose the editor font (such as Consolas or Lucida) and the font size
  • (取消)激活拼写检查、自动完成、自动关闭括号和代码检查
  • (De)activate spell checking, auto-completion, auto-closing of brackets, and code-checking

Overleaf 的集成拼写检查器用波浪线标记问题。只需右键单击它即可获得替换建议,如以下屏幕截图所示:

The integrated spell checker of Overleaf marks issues with a wavy line. Just right-click on it to get replacement suggestions, as shown in the following screenshot:

图 1.15 – Overleaf 中的拼写检查

图 1.15 – Overleaf 中的拼写检查

Figure 1.15 – Spellchecking in Overleaf

恰到好处拼写检查,还有更多。

Apropos spellchecking, there's more.

Writefull 的语法和语言反馈

Grammar and language feedback with Writefull

写满扩展检查语法并为您的文本提供措辞建议。它专为科学写作而设计,并接受了数百万篇研究期刊文章的训练。它可以纠正拼写错误、语法错误、词汇问题、标点符号等。

The Writefull Overleaf extension checks grammar and provides phrasing suggestions for your text. It's designed for scientific writing, and it's trained on millions of research journal articles. It can correct typos, grammar mistakes, vocabulary issues, punctuation, and more.

让我们看看它在我们之前的论文模板示例中的实际应用:

Let's see it in action on our previous thesis template example:

图 1.16 – 使用 Writefull 进行语法检查

图 1.16 – 使用 Writefull 进行语法检查

Figure 1.16 – Grammar checking with Writefull

虽然spellchecker 不会抱怨,经过训练的 Writefull 扩展 AI 会显示 129 个潜在问题,并对红色下划线的单词提供建议:

While the spellchecker doesn't complain, the trained AI of the Writefull extension shows 129 potential issues and gives suggestions to the words underlined in red:

  • 虽然可以替换为虽然
  • Though may be replaced by although.
  • 在正式写作中,Doesn't可以替换为doesnot 。
  • Doesn't may be replaced by does not, in formal writing.

在标题之后(在上图中),应该有一个牛津逗号,即列表末尾的“和”一词之前的逗号。

After headers (in the previous image), there should be an Oxford comma, that is, a comma before the word "and" at the end of a list.

你可以像我在本书中所做的那样轻松,不要那么正式,但你的论文或研究文章以及任何科学写作都可能从这些建议中受益。

You can take it easy as I do in this book, not so formal, but your thesis or research articles and any scientific writing may benefit from these suggestions.

Writefull 扩展最初可用于 Chrome 浏览器。宣布未来将支持其他网络浏览器,例如 Firefox。它的基本版本是免费的,您可以在他们的网站上阅读高级版本。

The Writefull extension was available for the Chrome browser at first. It was announced that other web browsers, such as Firefox, will be supported in the future. It's free in a basic version, and there is a premium version that you can read about on their website.

审查和评论

Reviewing and commenting

你可能注意到上一个屏幕截图中以黄色突出显示的文本和对话气泡符号。当您单击Review按钮时,评论栏会展开并显示评论:

You probably noticed the text highlighted in yellow and the speech bubble symbols in the previous screenshot. When you click the Review button, the review bar expands and the comments will be shown:

图 1.17 – 使用 Overleaf 查看和评论

图 1.17 – 使用 Overleaf 查看和评论

Figure 1.17 – Reviewing and commenting with Overleaf

你可以标记文本片段,点击添加评论,写下你的想法,也可以回复其他人的评论。这对您自己的写作以及与同事或编辑的合作都有帮助。

You can mark text snippets, click on Add comment, write what you think, and also reply to other people's comments. That helps both in your own writing and in collaborating with colleagues or an editor.

这个和前面提到的功能应该可以很好地了解当前的云 LaTeX 服务。

This and the previously mentioned features should provide a good insight into current cloud LaTeX services.

在我们的书籍示例中使用 Overleaf

Using Overleaf with our book examples

整套LaTeX 初学者指南代码示例可以同时在 Overleaf 中打开,只需单击一下。访问https://latexguide.org/code获取整个包,并拥有您自己的项目,其中包含所有书籍示例,随时可以编辑和编译。

The complete set of the LaTeX Beginner's Guide code examples can be opened in Overleaf simultaneously, with a single click. Visit https://latexguide.org/code to get the entire package and have your own project with all book examples included, ready to edit and compile.

以下部分将为您提供一种在使用本书时访问其他支持文档和参考资料的方法。

The following section will provide you with a way to access additional supporting documentation and references while working with this book.

访问文档

Accessing documentation

数百个 LaTeX 类和包可用。没有一本书可以单独解释它的所有特征。但大多数这些软件包都提供了很好的文档,您可以轻松打开和阅读。如果您按照自己的方式阅读本书并使用所提到的包的文档对其进行补充,那么您就走在了成为 LaTeX 高级用户的正确轨道上。

There are many hundreds of LaTeX classes and packages available. No book could ever explain all its features on its own. But most of those packages offer good documentation that you can easily open and read. If you work your way through this book and supplement it with the documentation of the packages mentioned, you're on the right track to becoming a LaTeX power user.

在接下来的章节中,您将了解许多提供附加功能的 LaTeX 包。为了做好准备,您应该只知道如何访问包文档。

In the following chapters, you will learn about many LaTeX packages that provide additional capabilities. To be prepared, you should just know how to access package documentation.

安装 LaTeX 后,您可以直接在计算机上打开软件包手册:

You can open a package manual directly on your computer after you have installed LaTeX:

  • 在 Windows 计算机上:在开始菜单中,选择TeX Live文件夹,然后单击 TeX Live 命令行。或者,只需运行 Windows cmd应用程序。
  • On Windows computer: In the Start menu, choose the TeX Live folder, and click TeX Live command-line. Alternatively, just run the Windows cmd app.
  • 在 Mac 或任何 Linux 计算机上:启动终端应用程序。
  • On a Mac or any Linux computer: Start a Terminal app.

然后,只需键入texdoc packagename并按Enter。例如,键入texdoc geometry打开一个 PDF 文档,该文档是geometry包的手册。

Then, just type texdoc packagename and press Enter. For example, typing texdoc geometry opens a PDF document that is the manual for the geometry package.

如果您没有安装 LaTeX,您可以在线获取文档。在您的浏览器中,打开https://texdoc.org/pkg/packagename。这只是一个模板 URL,所以如果你想要 geometry 包,你应该输入https://texdoc.org/pkg/geometry。对于 Overleaf 用户来说,这是一种简单的方法。

If you did not install LaTeX, you could obtain the documentation online. In your browser, open https://texdoc.org/pkg/packagename. That is just a template URL, so if you want the geometry package, you should type https://texdoc.org/pkg/geometry. That's an easy method for Overleaf users.

记住整本书

Remember throughout this book

稍后我们将经常在本书中引用包手册或包文档。请记住,您可以使用texdoc命令或在https://texdoc.org上打开文档,如前所述。

We will often refer to a package manual or package documentation in this book later on. Remember that you can open documentation with the texdoc command or on https://texdoc.org, as described previously.

最后,网上有很多与 LaTeX 相关的文档,包括教程和参考资料。我们将在第 14 章使用在线资源中详细讨论它。

Finally, there's a lot of LaTeX-related documentation available online, including tutorials and references. We will talk more about it in Chapter 14, Using Online Resources.

概括

Summary

我们在本章中了解了 LaTeX 的好处;很快,就轮到我们利用 LaTeX 的优点来获得最好的结果了。此外,我们还介绍了在计算机本地和云端在线安装、编辑和使用 LaTeX。

We learned in this chapter about the benefits of LaTeX; soon, it will be our turn to use the virtues of LaTeX to achieve the best possible results. Furthermore, we covered installing, editing, and using LaTeX, both locally on your computer and online in the cloud.

现在我们已经有了一个功能齐全且经过测试的 LaTeX 系统,我们可以准备编写自己的 LaTeX 文档了。在下一章中,我们将详细讨论格式化文本。

Now that we've got a functional and tested LaTeX system, we're ready to write our own LaTeX documents. In the next chapter, we will talk about formatting text in detail.

第 2 章:格式化文本和创建宏

Chapter 2: Formatting Text and Creating Macros

在上一章中,我们安装了 LaTeX 并使用 TeXworks 编辑器和 Overleaf 编写了我们的第一个文档。现在,我们将查看文本结构并关注文本细节及其格式。

In the last chapter, we installed LaTeX and used the TeXworks editor, as well as Overleaf, to write our first document. Now, we will look at the structure of text and focus on the text details and its formatting.

在本章中,我们将讨论以下内容:

In this chapter, we will talk about the following:

  • 使用逻辑格式
  • Working with logical formatting
  • 了解 LaTeX 如何读取我们的输入
  • Understanding how LaTeX reads our input
  • 修改文字字体
  • Modifying the text fonts
  • 创建我们自己的命令
  • Creating our own commands
  • 使用框来限制段落的宽度
  • Using boxes to limit the width of paragraphs
  • 断行和段落
  • Breaking lines and paragraphs
  • 关闭完全对齐
  • Turning off full justification
  • 显示报价
  • Displaying quotes

通过使用示例和尝试新功能,我们将学习 LaTeX 的一些基本概念。到本章结束时,您将熟悉命令和环境。您甚至可以定义自己的命令。

By working with examples and trying out new features, we shall learn some basic concepts of LaTeX. By the end of this chapter, you will be familiar with commands and environments. You will even be able to define your own commands.

既然已经开始高强度工作,当文档代码出现问题时,您可能会遇到错误信息。在这种情况下,您可以查看第 13 章故障排除,寻找可能的解决方案。

Now that you've started working intensively, you may encounter error messages when there's a problem with the document code. In such a case, you can look to Chapter 13, Troubleshooting, for possible solutions.

技术要求

Technical requirements

您要么需要在计算机上安装 LaTeX,要么可以使用 Overleaf。您还可以在本书的网页上在线编辑和编译所有示例:https://latexguide.org/chapter-02

You either need a LaTeX installation on your computer or you can use Overleaf. You can also edit and compile all the examples online on the book's web page: https://latexguide.org/chapter-02.

该代码也可在 GitHub 上找到:https://github.com/PacktPublishing/LaTeX-Beginner-s-Guide-2nd-Edition-/tree/main/Chapter_02_-_Formatting_Text_and_Creating_Macros

The code is also available on GitHub: https://github.com/PacktPublishing /LaTeX-Beginner-s-Guide-2nd-Edition-/tree/main/Chapter_02_-_Formatting_Text_and_Creating_Macros.

在本章中,我们将使用以下 LaTeX 包:hyphenatmicrotypeparskipurlxspace。如果您不在线工作,请确保已安装它们,或者您已按照建议安装了完整的 LaTeX。

In this chapter, we will use the following LaTeX packages: hyphenat, microtype, parskip, url, and xspace. If you don't work online, make sure you have them installed, or you have a full LaTeX installation as suggested.

使用逻辑格式

Working with logical formatting

在 LaTeX 文档中,我们应该不应用物理格式,例如,制作字粗体或斜体或在不同的大小。相反,我们应该使用逻辑格式,例如声明标题和作者并给出节标题。实际的格式设置,例如以大写字母打印标题和将章节标题设为粗体,是由 LaTeX 完成的。

Within a LaTeX document, we should not apply physical formatting, for example, making words bold or italic or in a different size. Instead, we should use logical formatting, such as declaring a title and the author and giving a section header. The actual formatting, such as printing the title in big letters and making a section heading bold, is done by LaTeX.

本书中的物理格式

Physical formatting in this book

在本章后面的一些示例中,我们将使用物理格式化命令,例如将单词设为粗体或斜体。但是,那是为了练习字体命令。本章的目标是在字体命令的帮助下定义我们自己的逻辑命令。

In some examples later in this chapter, we will use physical formatting commands, such as making words bold or italic. However, that's for practicing font commands. The goal of this chapter is to define our own logical commands with the help of font commands.

在良好的 LaTeX 文档中,物理格式仅在逻辑格式命令的定义中使用。如果我们需要一些格式样式,例如关键字,我们将在文档序言中定义一个合适的逻辑命令。在文档正文中,我们应该只使用逻辑格式命令。这使我们在整个文本中具有一致的格式,并且每当我们改变对格式细节的想法时,我们都可以修改序言中的逻辑命令。我们将在下一节中进行介绍。

In a good LaTeX document, physical formatting is only used within the definition of logical formatting commands. If we need some format style, such as for keywords, we will define a suitable logical command in the document preamble. In the document body text, we should only use the logical formatting commands. This gives us consistent formatting throughout the text, and whenever we change our mind on formatting details, we can modify the logical commands in the preamble. We will go through this in the next sections.

首先,要了解典型的文档结构,让我们从一个简短的说明性示例开始。

First, to understand the typical document structure, let's start with a short, illustrative example.

创建带有标题和标题的文档

Creating a document with a title and heading

我们将创建一个简短的例子一些基本格式。它应包括标题、作者姓名、日期、标题和一些常规文本:

We will create a short example with some basic formatting. It shall include a title, the author's name, the date, a heading, and some regular text:

  1. 在您的编辑器中输入以下代码以启动一个小文档:

    \documentclass[a4paper,11pt]{文章}

  2. Type the following code into your editor to start a small document:

    \documentclass[a4paper,11pt]{article}

  3. 指定标题、作者和日期:

    \title{例2}

    \作者{我的名字}

    \日期{2021 年 5 月 5 日}

  4. Specify the title, author, and date:

    \title{Example 2}

    \author{My name}

    \date{May 5, 2021}

  5. 开始文档:

    \开始{文档}

  6. Begin the document:

    \begin{document}

  7. 让 LaTeX 打印完整的标题,其中包括作者和日期:

    \maketitle

  8. Let LaTeX print the full title, which will include the author and date:

    \maketitle

  9. 创建一个节标题并添加一些文本:

    \section{这是什么?}

    这是我们的第二份文件。它包含一个标题和一个带有文本的部分。

    \end{文档}

  10. Make a section heading and add some text:

    \section{What's this?}

    This is our second document. It contains a title and a section with text.

    \end{document}

  11. 单击“保存”按钮(或按Ctrl + S)保存文档。为其命名,例如example2.tex
  12. Save the document by clicking the Save button (or press Ctrl + S). Give it a name, such as example2.tex.
  13. 通过单击排版按钮(或按Ctrl + T)编译文档;这会将您的代码转换为 PDF 文件。
  14. Compile the document by clicking the Typeset button (or press Ctrl + T); this translates your code into a PDF file.
  15. 查看输出:
  16. View the output:
图 2.1 – 带有标题的文本

图 2.1 – 带有标题的文本

Figure 2.1 – Text with a heading

TeXworks立即编辑在您按下排版按钮后显示 PDF 预览。同时,还会创建一个 PDF 文件。在这种情况下,它称为example2.pdf并且与原始代码文件example2.tex位于同一文件夹中。

The TeXworks editor immediately shows the PDF preview after you press the Typeset button. At the same time, a PDF file is also created. In this case, it's called example2.pdf and it's in the same folder as your original code file, example2.tex.

在第一章中,我们谈到了逻辑格式化;让我们从这个角度来看这个例子。我们告诉 LaTeX 以下内容:

In the first chapter, we talked about logical formatting; let's look at this example from that point of view. We told LaTeX the following:

  • 我们的文档是文章类型的。它将使用 11 磅的基本字体打印在 A4 纸上。
  • Our document is of the article type. It will be printed on A4 paper using a size of 11 points for the base font.
  • 文档的标题是Example 2
  • The title of the document is Example 2.
  • 它显示作者的名字。
  • It shows the author's name.
  • 该文件写于2021 年 5 月 5 日
  • The document was written on May 5, 2021.

关于文件的内容,我们声明如下:

Concerning the content of the document, we stated the following:

  • 它以标题开头。
  • It begins with a title.
  • 第一部分包括标题这是什么?
  • The first section includes the heading What's this?
  • 标题之后是文本这是我们的第二份文件。它包含一个标题和一个带有文本的部分。.
  • Following the heading is the text This is our second document. It contains a title and a section with text..

请注意,我们没有选择标题或标题的字体大小,我们也没有做任何事情粗体或居中。这样的格式化是由 LaTeX 完成的,但是您可以自由地告诉 LaTeX 它实际上应该是什么样子。

Note we did not choose the font size of the title or heading, and neither did we make something bold or centered. Such formatting is done by LaTeX but nevertheless, you're free to tell LaTeX how it actually should look.

自动保存

Auto-saving

一旦我们保存了文档,我们就不需要再次按下保存按钮。当我们点击Typeset按钮时,TeXworks 会自动保存文档。

Once we have saved a document, we do not need to press the Save button again. TeXworks automatically saves the document when we click the Typeset button.

探索文档结构

Exploring the document structure

让我们看看我们刚刚创建的示例的详细信息。LaTeX 文档不是独立的——通常,该文档基于通用模板。这样的基本模板称为。它提供可定制的功能,通常是为特定目的而构建的。有书籍、期刊文章、信件、演示文稿、海报等课程;数百个可靠的类可以在 Internet 档案中找到,但在安装 TeX Live 后也可以在您的计算机上找到。在我们的示例中,我们选择了文章类,这是一个适用于较小文档的标准 LaTeX 类。

Let's look at the details of the example we just created. A LaTeX document doesn't stand alone—commonly, the document is based on a versatile template. Such a fundamental template is called a class. It provides customizable features, usually built for a certain purpose. There are classes for books, journal articles, letters, presentations, posters, and many more; hundreds of reliable classes can be found in internet archives, but also on your computer after you've installed TeX Live. In our example, we have chosen the article class, a standard LaTeX class suitable for smaller documents.

第一行以\documentclass开头。这个词以反斜杠开头;这样的词称为命令。我们已经使用命令来指定类并国家文件本章第一个示例中的属性:\title\author\date。这些命令存储属性;他们不打印任何东西。

The first line starts with \documentclass. This word begins with a backslash; such a word is called a command or a macro. We already used commands to specify the class and to state document properties in our first example in this chapter: \title, \author, and \date. These commands store the properties; they don't print something.

这第一部分该文件被称为文件的序言。这是我们选择类、指定属性以及通常进行文档范围定义的地方。

This first part of the document is called the preamble of the document. This is where we choose the class, specify properties, and in general make document-wide definitions.

\begin{document}标记序言的结尾和实际文档的开头。\end{document}标记文档的结尾。LaTeX 将忽略后面的所有内容。通常,由\begin\end命令对构成的这样一段代码称为environment

\begin{document} marks the end of the preamble and the beginning of the actual document. \end{document} marks the end of the document. Everything that follows would be ignored by LaTeX. Generally, such a piece of code that's framed by a \begin and \end command pair is called an environment.

在实际文档中,我们使用了\maketitle命令,它以格式良好的方式打印标题、作者和日期。使用\section命令,我们生成了一个标题,比普通文本更大更粗。然后,我们让一些文本跟随。我们在序言之后所写的,在文档环境中,将被打印出来。但是,序言本身永远不会产生任何输出。

In the actual document, we've used the \maketitle command, which prints the title, author, and date in a nicely formatted manner. With the \section command, we produced a heading, bigger and bolder than normal text. Then, we let some text follow. What we wrote after the preamble, in the document environment, will be printed out. However, the preamble itself will never produce any output.

现在您已经了解了命令的样子,让我们详细了解一下命令语法。

Now that you've seen what commands look like, let's look at command syntax in detail.

了解 LaTeX 命令

Understanding LaTeX commands

LaTeX 命令以反斜杠开头,后跟大小写字母,通常命名为以描述的方式。也有例外:您会看到一些命令由一个反斜杠和一个特殊字符组成。

LaTeX commands begin with a backslash, followed by big or small letters, and are usually named in a descriptive way. There are exceptions: you will see some commands consisting of a backslash and just one special character.

命令可以有参数,即决定命令以何种方式工作的选项。我们作为参数传递的值称为arguments。他们是在大括号或方括号中给出,我们现在将解释。

Commands can have parameters, that is, options that determine in which way the command does its work. The values that we hand over as parameters are called arguments. They are given in curly braces or square brackets, as we will explain now.

因此,调用命令可以如下所示:

So, calling a command can look like this:

\命令

\command

或者,它看起来像这样:

Or, it can look like this:

\命令{参数}

\command{argument}

或者,它看起来像这样:

Or, it can look like this:

\command[可选参数]{argument}

\command[optional argument]{argument}

可以有多个参数,每个参数都在大括号或方括号中。花括号中的参数是强制性的。如果命令被定义为需要参数,则必须给出一个。例如,如果我们没有声明类名,调用\documentclass将是徒劳的。

There could be several arguments, each of them in braces or brackets. Arguments in curly braces are mandatory. If a command is defined to require an argument, one has to be given. For example, calling \documentclass would be futile if we haven't stated a class name.

方括号中的参数是可选的;它们可能会被给出,但不是必须的。如果没有提供可选参数,该命令将使用默认参数。例如,在第 1 章的第一个示例中,LaTeX入门我们写了\documentclass{article}。本文档使用 10 磅的基本字体大小排版,因为这是该类的默认基本字体大小。在第二个文档中,我们写了\documentclass[a4paper,11pt]{article};在这里,我们用给定的值替换了默认值,所以现在文档将使用 11 点的基本字体大小调整为 A4 纸。

Arguments in square brackets are optional; they may be given but it's not a must.If no optional argument is provided, the command will use a default one.For instance, in the first example in Chapter 1, Getting Started with LaTeX, we wrote \documentclass{article}. This document was typeset with a base font size of 10 points because this is the class's default base font size. In the second document, we wrote \documentclass[a4paper,11pt]{article}; here, we replaced the default values with the given values, so now the document will be adjusted for A4 paper using a base font size of 11 points.

命令、宏和声明

Commands, macros, and declarations

大多数乳胶命令,包括我们定义的命令我们自己,由其他命令组成。这就是 LaTeX 命令的原因也称为,术语命令可互换使用。一个命令或宏,不打印任何东西但仅更改当前设置,例如字体形状或文本对齐方式,也称为声明

Most LaTeX commands, including those we define ourselves, consist of other commands. That's why LaTeX commands are also called macros, and the terms macro and command are used interchangeably. A command or macro that doesn't print something but just changes current settings, such as the font shape or text alignment, is also called a declaration.

现在,让我们看看环境的语法。

Now, let's look at the syntax of environments.

了解 LaTeX 环境

Understanding LaTeX environments

LaTeX 环境以\begin开始并以\end结束。这两个命令都需要名称环境作为他们的论点。

LaTeX environments start with \begin and end with \end. Both commands require the name of the environment as their argument.

简单的环境看起来像这样:

Simple environments look like this:

\开始{名称}

\begin{name}

    ……

    …

\结束{名称}

\end{name}

这样的environments 可用于每个名为\name的声明。

Such environments can be used for each declaration called \name.

像命令一样,环境可能有参数。与命令的情况完全一样,强制参数写在花括号中,可选参数写在方括号中。所以,你会遇到这样的环境:

Like commands, environments may have arguments. Exactly like in the case of commands, mandatory arguments are written in curly braces and optional arguments in square brackets. So, you will encounter an environment like this:

\begin{名称}{参数}

\begin{name}{argument}

    ……

    …

\结束{名称}

\end{name}

你还会遇到这样的环境:

You will also encounter environments like this:

\begin{名称}[可选参数]{参数}

\begin{name}[optional argument]{argument}

    ……

    …

\结束{名称}

\end{name}

环境就像具有内置作用域的声明。随着\begin,环境介绍布局、字体或其他方面的更改特性。必须有一个\end命令,此更改将被取消。环境名称的影响被分隔到\begin{name}\end{name}之间的代码段。

Environments are like declarations with a built-in scope. With \begin, the environment introduces a change in layout, font, or other properties. There must be an \end command, where this change will be canceled. The effect of the environment name is delimited to the piece of code between \begin{name} and \end{name}.

此外,在一个环境中使用的所有本地声明的效果将与周围环境一起结束。

Furthermore, the effect of all local declarations used inside an environment will end together with the surrounding environment.

现在我们知道了 LaTeX 命令和环境的语法,让我们看看 LaTeX 如何处理我们输入的内容。

Now that we know the syntax of LaTeX commands and environments, let's see how LaTeX treats what we type.

了解 LaTeX 如何读取我们的输入

Understanding how LaTeX reads our input

在我们之前继续写,我们来看看 LaTeX 是如何理解我们输入的内容的:

Before we continue writing, let's look at how LaTeX understands what we type:

  • 除了简单的字母字符外,我们还可以直接键入(或复制和粘贴)重音字符,例如 ä、ü 和 ö,以及来自其他语言的更多字符,例如希腊语或俄语。
  • Besides simple alphabet characters, we can directly type (or copy and paste) accented characters, such as ä, ü, and ö, as well as further characters from other languages, such as Greek or Russian.
  • 输入代码中的空格将在输出文档中显示为空格。几个连续的空格被视为一个空格。
  • A space in the input code will appear as a space in the output document. Several consecutive spaces are treated as one space.
  • 源代码中的行尾被视为空格。
  • An end of a line in the source code is treated as a space.
  • 源代码中的空行被视为分段符。
  • An empty line in the source code is treated as a paragraph break.

有些字符具有特殊含义:

There are some characters with special meanings:

  • 反斜杠\启动 LaTeX 命令或 LaTeX 宏。
  • A backslash, \, starts a LaTeX command or a LaTeX macro.
  • 花括号和方括号用于命令参数。
  • Curly braces and square brackets are used for command arguments.
  • 美元符号$开始和结束数学模式,我们将在第 9 章编写数学公式”中探讨该模式。
  • A dollar sign, $, starts and ends math mode, which we will explore in Chapter 9, Writing Math Formulas.
  • 百分号%告诉 LaTeX 忽略该行的其余部分。
  • A percent sign, %, tells LaTeX to ignore the rest of the line.

让我们扩展最后一点:百分号引入了注释。百分号之后直到行尾的所有内容都将被 LaTeX 忽略并且不会被打印出来。这使您能够将注释插入到文档中。它通常用于 LaTeX 模板中,以告知用户模板做什么或要求用户在某个时刻做什么。请注意,通常表现为空格的行尾在百分号后也将被忽略。

Let's expand upon that last point: the percent sign introduces a comment. Everything following a percent sign until the end of the line will be ignored by LaTeX and won't be printed out. This enables you to insert notes into your document. It's often used in LaTeX templates to inform the user of what the template does or requires the user to do at a certain point. Note that the end of the line, normally behaving as a space, will also be ignored after a percent sign.

通过反复试验简化实验

Easing experimenting by trial and error

如果要暂时禁用命令,插入百分号而不是删除命令可能更有利。这样,您就可以通过删除百分号轻松撤消此更改。

If you want to disable a command temporarily, it may be favorable to insert a percent sign instead of deleting the command. That way, you're able to undo this change easily by removing the percent sign.

如果那是百分号是如何工作的,如果我们想在文本中写 100%,我们应该怎么做?那么其他特殊符号呢?让我们在下一节中弄清楚如何解决该问题。

If that is how the percent sign works, what should we do if we want to write 100% in our text? And what about the other special symbols? Let's figure out how to solve that issue in the next section.

打印特殊符号

Printing out special symbols

普通文本多为大小写字母、数字、标点符号你可以简单地输入你的编辑器。但是,有些字符是为 LaTeX 命令保留的,不能直接使用。我们已经遇到过这样的字符,包括百分号和花括号。要解决此问题,可以使用 LaTeX 命令来打印此类符号。

Common text mostly contains uppercase and lowercase letters, digits, and punctuation characters that you can simply type into your editor. However, some characters are reserved for LaTeX commands and cannot be used directly. We already encountered such characters, including the percent sign and curly braces. To fix this issue, there are LaTeX commands to print such symbols.

我们将编写一个非常简短的示例,打印出一定数量的美元和百分比数字,以及一些其他符号:

We will write a very short example printing out an amount of dollars and a percent number, along with some other symbols:

  1. 创建一个新文档并输入以下行:

    \文档类{文章}

    \开始{文档}

    陈述#1:

    100 美元的 50% 等于 50 美元。

    更多特殊符号是 \&、\_、\{ 和 \}。

    \end{文档}

  2. Create a new document and enter the following lines:

    \documentclass{article}

    \begin{document}

    Statement \#1:

    50\% of \$100 equals \$50.

    More special symbols are \&, \_, \{ and \}.

    \end{document}

  3. 单击排版按钮编译文档。
  4. Click the Typeset button to compile the document.
  5. 查看输出:
  6. Check out the output:
图 2.2 – 特殊符号

图 2.2 – 特殊符号

Figure 2.2 – Special symbols

通过在特殊符号前加上反斜杠,我们将其变成了 LaTeX 命令。此命令的唯一目的是打印出该符号。

By putting a backslash before a special symbol, we turned it into a LaTeX command. The only purpose of this commend is to print out that symbol.

打印反斜杠

Printing the backslash

您可能想知道如何打印反斜杠。打印反斜杠的命令是\textbackslash。如果您想知道\\的用途,可以将其用作换行符的快捷方式。这可能看起来有点奇怪,但换行符经常出现,而输出中很少需要反斜杠,因此选择了这个快捷方式。

You may be wondering how to print a backslash. The command for printing a backslash is \textbackslash. If you would like to know what \\ might be used for, it is used as a shortcut for a line break. That may seem a bit odd, but line breaks occur frequently whereas backslashes are rarely needed in the output, therefore this shortcut has been chosen.

有一个我们可以使用丰富的符号来表示数学公式、国际象棋符号、十二生肖、乐谱等等。我们暂时不需要处理这些符号,但我们将在第 9 章编写数学公式”中返回到该主题,届时我们将需要符号来排版数学公式。

There's a wealth of symbols that we can use for math formulas, chess notation, zodiac signs, music scores, and more. We don't need to deal with those symbols for now, but we shall return to that subject in Chapter 9, Writing Math Formulas, when we will need symbols to typeset math formulas.

现在我们知道了如何输入纯文本,让我们来看看如何格式化它。

Now that we know how to enter pure text, let's find out how we can format it.

修改文字字体

Modifying the text fonts

乳胶已经自动进行一些格式化;例如,我们已经看到章节标题比普通文本更大并且是粗体。现在我们将学习如何自己修改文本的外观。

LaTeX already does some formatting automatically; for example, we've seen that section headings are bigger than normal text and bold-faced. Now we will learn how to modify the appearance of the text ourselves.

调整字体形状

Adjusting the font shape

在这个例子中,我们将在文本中强调一个重要的词,我们将看到如何使单词以粗体、斜体或倾斜显示。我们还将弄清楚如何突出显示已强调的文本特定部分中的单词。

In this example, we will emphasize an important word in our text, and we will see how to make words appear in bold, italic, or slanted. We shall also figure out how to highlight words in a specific part of the text that's already emphasized.

让我们来看看:

Let's take a look:

  1. 创建一个包含以下代码的新文档:

    \文档类{文章}

    \开始{文档}

    文本可以\emph{强调}。

    除了 \textit{italics} 之外,单词还可以是

    \textbf{粗体}、\textsl{倾斜}或排版

    在 \textsc {小型大写字母}中。

    这样的命令可以是 \textit{\textbf{nested}}。

    \emph{看看 \emph{emphasizing} 嵌套时的样子。}

    \end{文档}

  2. Create a new document containing the following code:

    \documentclass{article}

    \begin{document}

    Text can be \emph{emphasized}.

    Besides from \textit{italics}, words can be

    \textbf{bold}, \textsl{slanted}, or typeset

    in \textsc {Small Caps}.

    Such commands can be \textit{\textbf{nested}}.

    \emph{See how \emph{emphasizing} looks when nested.}

    \end{document}

  3. 单击排版并查看输出:
  4. Click Typeset and have a look at the output:
图 2.3 – 强调短语

图 2.3 – 强调短语

Figure 2.3 – Emphasizing phrases

起初,我们使用\emph命令,将一个单词作为该命令的参数。此参数将以斜体排版,因为这是 LaTeX 强调文本的默认方式。

At first, we used the \emph command, giving one word as an argument to this command. This argument will be typeset in italic because this is the default way LaTeX emphasizes text.

文本格式化命令通常看起来像\text**{argument},其中**代表两个字母的缩写,例如bf代表粗体,it代表斜体,sl代表倾斜。正如我们在示例中看到的那样,参数将被相应地格式化。命令之后,后续文本将继续按照命令之前的方式进行排版——恰好在右大括号之后,标记参数的结尾。

Text-formatting commands usually look like \text**{argument}, where ** stands for a two-letter abbreviation such as bf for bold face, it for italic, and sl for slanted. The argument will then be formatted accordingly, as we've seen in our example. After the command, the subsequent text will continue being typeset as it was before the command—precisely after the closing curly brace, marking the end of the argument.

我们嵌套了\textit\textbf命令,这允许我们实现这些样式的组合,并且文本以斜体和粗体显示。

We nested the \textit and \textbf commands, which allowed us to achieve a combination of those styles, and the text appears in both italic and bold.

大多数字体如果应用两次,命令将显示相同的效果,例如\textbf{\textbf{words}}。在这里,话不会变得更大胆。

Most font commands will show the same effect if they are applied twice, such as \textbf{\textbf{words}}. Here, the words won't become bolder.

但是\emph 的行为不同。我们已经看到\emph将文本更改为斜体,但是如果我们在一段已经是斜体的文本上使用\emph ,它将从斜体变为直立字体。想象一个重要的定理完全用斜体排版,你想突出这个定理中的一个词;这个词不应该是斜体,而是再次格式化为直立字体。

But \emph behaves differently. We've seen that \emph changes text to italic, but if we use \emph on a piece of text that is already in italic, it will change from italic to upright font. Imagine an important theorem completely typeset in italic and you would like to highlight a word inside this theorem; that word should not be in italic but formatted as upright font again.

明智地改变字体形状

Change the font shape sensibly

组合字体形状,例如同时标记为粗体和斜体,可能被认为是一种有问题的样式选择。明智且一致地更改字体形状。

Combining font shapes, such as marking bold and italic at the same time, might be considered a questionable style choice. Change the font shape wisely—and consistently.

选择字体系列

Choosing the font family

默认值LaTeX 字体是衬线字体(也称为罗马字体)。那表示附有称为衬线的细线或笔划到字母。如果没有这样的衬线,我们称该字体为无衬线字体。

The default LaTeX font is a serif font (also called a Roman font). That means small lines or strokes, called serifs, are attached to letters. If such serifs are absent, we call the font a sans-serif font.

比较图2.4中的两条线。仔细观察第一个字母T,它清楚地显示了衬线字体和无衬线字体之间的区别:

Compare the two lines in Figure 2.4. Look closely at the first letter, T, which clearly shows the difference between serif and sans-serif fonts:

图 2.4 – Serif 与 sans-serif 字体

图 2.4 – Serif 与 sans-serif 字体

Figure 2.4 – Serif versus sans-serif font

这些不同的字体类型称为字体系列字体

These different types of fonts are called font families or typefaces.

其他字体是等宽的;在这里,所有字母都具有相同的宽度。等宽字体也称为打字机字体。

Another typeface is monospaced; here, all letters have the same width. Monospaced fonts are also called typewriter fonts.

让我们切换小型示例文档中的字体系列。我们将从粗体文本开始,但粗体文本衬线看起来很沉重。因此,我们将改用无衬线粗体文本。下面的文本将包含一个互联网地址,我们将选择一种打字机字体来强调它。

Let's switch font families in a small example document. We will start with bold text, but bold text with serif looks very heavy. So, we will use sans-serif bold text instead. The following text will contain an internet address, and we will choose a typewriter font to emphasize it.

请遵循以下说明:

Follow these instructions:

  1. 使用以下代码创建一个 LaTeX 文档:

    \文档类{文章}

    \开始{文档}

    \textsf{\textbf{在 Internet 上获取帮助}}

    \texttt{https://latex.org} 是 \LaTeX 的支持论坛。

    \end{文档}

  2. Create a LaTeX document with the following code:

    \documentclass{article}

    \begin{document}

    \textsf{\textbf{Get help on the Internet}}

    \texttt{https://latex.org} is a support forum for \LaTeX.

    \end{document}

  3. 点击排版,查看结果:
  4. Click on Typeset and look at the result:
图 2.5 – 带有 URL 的文本

图 2.5 – 带有 URL 的文本

Figure 2.5 – Text with a URL

在这里,我们遇到了更多的字体命令——通过使用\textsf,我们在标题行中选择了无衬线字体,并且我们使用\texttt命令来获取互联网地址的打字机字体。这些命令可以像我们之前学过的字体命令一样使用。

Here, we encountered further font commands—by using \textsf, we've chosen the sans-serif font in the heading line, and we used the \texttt command to get the typewriter font for the internet address. Those commands can be used just like the font commands we've learned about before.

衬线是字母笔划末尾的那些小装饰细节,通过引导读者的视线沿着线条提高可读性;因此,它们被广泛用于印刷书籍和报纸。

Serifs, those small decorative details at the end of a letter's strokes, improve readability by leading the reader's eyes along the line; therefore, they are widely used in printed books and newspapers.

标题通常没有衬线。Sans-serif 字体也是屏幕文本的不错选择,因为它们在低分辨率屏幕或小字体的手机显示屏上具有更好的可读性。电子书和互联网页面上的文本通常首选无衬线字体。

Headings are often done without serifs. Sans-serif fonts are also a good choice for screen text because of their better readability on lower-resolution screens or on mobile phone displays with small font sizes. Sans-serif fonts are often preferred for text in e-books and on internet pages.

等宽或打字机字体是编写计算机程序源代码的首选,无论是在印刷品还是在文本编辑器中。与我们前面的例子一样,本书通常使用打字机字体来区分源代码和网址与普通文本。

Monospaced or typewriter fonts are preferred for writing the source code of computer programs, both in print and in text editors. As in our previous example, this book generally uses a typewriter font to distinguish source code and web addresses from normal text.

我们看到的命令将格式应用于花括号中参数中的文本。LaTeX 还提供不带参数的命令,其工作方式类似于开关。

The commands we've seen applied formatting to the text in the argument in curly braces. LaTeX also provides commands without arguments, which work like switches.

使用以下说明,我们将使用字体系列切换命令修改前面的示例:

Using the following instructions, we will modify the previous example using font family switching commands:

  1. 编辑前面的示例以获得以下代码:

    \文档类{文章}

    \开始{文档}

    \sffamily\bfseries 在 Internet 上获取帮助

    \normalfont\ttfamily https://latex.org\normalfont\ 是

    \LaTeX 的支持论坛。

    \end{文档}

  2. Edit the previous example to get the following code:

    \documentclass{article}

    \begin{document}

    \sffamily\bfseries Get help on the Internet

    \normalfont\ttfamily https://latex.org\normalfont\ is

    a support forum for \LaTeX.

    \end{document}

  3. 单击“排版”进行编译。
  4. Click on Typeset to compile.
  5. 将输出与前面的示例进行比较;一样的。
  6. Compare the output to the previous example; it's the same.

通过使用\sffamily命令,我们切换到无衬线字体。\bfseries命令将文本切换为粗体。我们使用\normalfont命令返回到默认的 LaTeX 字体,然后我们使用\ttfamily命令切换到打字机字体。在 internet 地址之后,我们再次使用\normalfont来切换到默认字体。

By using the \sffamily command, we switched to the sans-serif typeface. The \bfseries command switched the text to bold. We used the \normalfont command to return to the default LaTeX font, and then we used the \ttfamily command to switch to a typewriter font. After the internet address, we used \normalfont again to switch to the default font.

这样的切换命令本身不产生任何输出,但它们会影响后面的文本,所以它们是声明

Such switching commands don't produce any output themselves, but they will affect the text that follows it, so they are declarations.

让我们总结一下字体命令及其相应的声明及其含义:

Let's summarize the font commands and their corresponding declarations together with their meanings:

图 2.6 – 字体命令

图 2.6 – 字体命令

Figure 2.6 – Font commands

强调的注意事项

Note on emphasizing

\emph对应的声明是\em

The corresponding declaration to \emph is \em.

用大括号限制命令的效果

Confining the effect of commands by braces

在前面的例子中,我们写了\normalfont来将字体切换回默认字体,但是还有另一种方法。我们将使用大括号告诉 LaTeX 在哪里应用命令以及在哪里停止它:

In the previous example, we wrote \normalfont to switch the font back to the default font, but there's another way. We shall use curly braces to tell LaTeX where to apply a command and where to stop it:

  1. 缩短并修改生成图 2.3 的字体形状示例以获得此代码:

    \文档类{文章}

    \开始{文档}

    除了 {\itshape italics} 之外,单词还可以是

    {\bfseries bold}、{\slshape slanted} 或排版

    在 {\scshape 小型大写字母}中。

    \end{文档}

  2. Shorten and modify our font shape example that produced Figure 2.3 to get this code:

    \documentclass{article}

    \begin{document}

    Besides from {\itshape italics}, words can be

    {\bfseries bold}, {\slshape slanted}, or typeset

    in {\scshape Small Caps}.

    \end{document}

  3. 单击排版并检查输出:
  4. Click on Typeset and check out the output:
图 2.7 – 使用声明改变字体粗细和形状

图 2.7 – 使用声明改变字体粗细和形状

Figure 2.7 – Using declarations to change the font weight and shape

当我们使用声明更改字体时,我们以左花括号开始,然后是字体声明命令。该命令的效果一直持续到我们用相应的右大括号停止它为止。

When we change the font using a declaration, we start with an opening curly brace, and then the font declaration command follows. The effect of that command lasts until we stop it with the corresponding closing brace.

左花括号告诉 LaTeX 开始一个。以下命令对后续文本有效,直到右大括号结束该组。组可以嵌套如下:

An opening curly brace tells LaTeX to begin a group. The following commands are valid for the subsequent text until a closing curly brace ends the group. Groups can be nested as follows:

普通文本,{\sffamily sans serif text {\bfseries and bold}}。

Normal text, {\sffamily sans serif text {\bfseries and bold}}.

一个地区命令有效称为其作用域。我们必须小心完成每个组。对于每个左大括号,必须有一个右大括号。

The area where a command is valid is called its scope. We have to be careful to complete each group. For every opening brace, there has to be a closing brace.

因此,简而言之,组由大括号定义,它们包含并限制本地命令的效果。

So, in short, groups are defined by curly braces and they contain and confine the effect of local commands.

探索字体大小

Exploring font sizes

现在我们将尝试使用 LaTeX 的默认字体大小命令提供的每种字体大小:

Now we will try out every font size available with LaTeX's default font size commands:

  1. 使用以下代码创建文档:

    \文档类{文章}

    \开始{文档}

    \tiny 我们 \scriptsize 开始 \footnotesize 非常

    \smallsmall, \normalsize 得到 \large 大 \Large

    和 \LARGE 更大,\巨大巨大,\巨大巨大!

    \end{文档}

  2. Create a document with the following code:

    \documentclass{article}

    \begin{document}

    \tiny We \scriptsize start \footnotesize very

    \smallsmall, \normalsize get \large big \Large

    and \LARGE bigger, \huge huge, \Huge gigantic!

    \end{document}

  3. 单击Typeset并观察输出:
  4. Click on Typeset and observe the output:
图 2.8 – 字体大小

图 2.8 – 字体大小

Figure 2.8 – Font sizes

我们使用了所有 10 种可用的字体大小声明,从小的\tiny开始,到真正大的\Huge结束。没有相应的带参数的命令,所以我们必须使用花括号来分隔它们的范围,正如我们之前学到的那样。

We used all 10 available font size declarations, starting small with \tiny and ending really big with \Huge. There are no corresponding commands taking arguments, so we would have to use curly braces to delimit their scope, as we learned before.

实际生成的字体大小与基本字体大小成比例。如果您的文档有 12 磅的基本字体,那么\tiny会导致文本大于 10 磅的基本字体。

The actual resulting font size scales with the base font size. If your document has a base font of 12 points, then \tiny would result in text bigger than the base font of 10 points.

如果您希望获得与 LaTeX 用于脚注相同的大小,请使用\ footnotesize;如果您希望创建大小与 LaTeX 下标和上标匹配的样式,请使用 \ scriptsize 。文档类提供精心挑选和非常适合的字体大小选择,因此您通常不需要设置特定的物理大小。这个和其他高级字体调整命令在LaTeX CookbookPackt Publishing 的第 3 章“调整字体”中介绍。

Use \footnotesize if you wish to get the same size LaTeX uses for footnotes or use \scriptsize if you wish to create a style with a size matching LaTeX subscripts and superscripts. Document classes provide carefully selected and well-suited font size selections, so you normally don't need to set a certain physical size. This and other advanced font tweaking commands are covered in Chapter 3, Adjusting Fonts, in the LaTeX Cookbook, Packt Publishing.

为了练习,我们在本节中使用了许多预定义的字体命令。下一个层次是创建我们的自己的逻辑格式命令来使用它们而不是文档正文文本中的物理字体命令。

For practice, we used many predefined font commands in this section. The next level is to create our own logical formatting commands to use them instead of physical font commands within the document body text.

创建我们自己的命令

Creating our own commands

如果您经常在文档中使用相同的术语,那么一次又一次地输入它会很烦人。如果您稍后决定更改该术语或其格式怎么办?为了避免搜索并替换整个文档中的术语,LaTeX 允许您在序言中定义自己的命令。

If you're frequently using the same term in your document, it would be annoying to type it again and again. What if you later decide to change that term or its formatting? To avoid searching and replacing the term in the whole document, LaTeX allows you to define your own commands in your preamble.

请记住:由其他命令组成的命令称为,这就是我们所说的现在将定义。基本上,我们选择一个新的宏名称并定义要在该宏中使用的文本或命令的序列。然后,当我们想要执行一个动作时,我们只需要使用宏的名称。

Remember: a command that consists of other commands is called a macro, and that's what we will define now. Basically, we choose a new macro name and define the sequence of text or commands to be used in that macro. Then, when we want to perform an action, we just need to use the macro's name.

我们将从基本上是缩写的简单宏开始。

We will start with simple macros that are basically abbreviations.

对简单文本使用宏

Using macros for simple text

宏可以避免我们重复长单词或短语,并且可以充当占位符。我们可以更改宏的内容以使用该短语的不同版本更新整个文档。

Macros can save us from repeating long words or phrases and can act as placeholders. We can change the content of the macro to update the whole document with a different version of that phrase.

在这里,我们将定义一个打印出TeX 用户组( TUG )名称的简短命令:

Here, we will define a short command that prints out the name of the TeX Users Group (TUG):

  1. 在新文档中键入此代码:

    \文档类{文章}

    \newcommand{\TUG}{\TeX\ 用户组}

    \开始{文档}

    \section{\TUG}

    \TUG\ 是一个为使用

    \TeX\ 或 \LaTeX。

    \end{文档}

  2. Type this code into a new document:

    \documentclass{article}

    \newcommand{\TUG}{\TeX\ Users Group}

    \begin{document}

    \section{The \TUG}

    The \TUG\ is an organization for people who use

    \TeX\ or \LaTeX.

    \end{document}

  3. 点击排版,查看结果:
  4. Click on Typeset and look at the result:
图 2.9 – 使用我们的第一个宏

图 2.9 – 使用我们的第一个宏

Figure 2.9 – Using our first macro

突出显示行中的\newcommand定义了我们的命令。第一个参数是我们为命令选择的名称,第二个参数是我们希望它在文档中打印的文本。

\newcommand in the highlighted line defines our command. The first argument is the name we chose for the command, and the second argument is the text we want it to print out in the document.

现在,每当我们在文档中键入\TUG时,就会出现完整的名称。如果我们稍后决定更改名称或其格式,我们只需要更改此\new命令行。然后,更改将应用​​于整个文档。

Now, whenever we type \TUG in our document, the complete name will appear. If we later decide to change the name or its formatting, we just need to change this \newcommand line. Then, the change will be applied to the whole document.

您可以在命令定义中使用格式化命令。假设你想更改所有出现此名称的格式,以小写字母排版;只需将定义更改为以下内容:

You may use formatting commands inside your command definition. Let's say you would like to change the formatting of all occurrences of this name to be typeset in small caps; just change the definition to the following:

\newcommand{\TUG}{\textsc{TeX 用户组}}

\newcommand{\TUG}{\textsc{TeX Users Group}}

您还看到我们使用了\TeX命令。这个缩写命令只是打印出排版系统的名称,格式与其徽标相同。\LaTeX 的工作原理类似。

You have also seen that we've used the \TeX command. This abbreviation command just prints out the name of the typesetting system, formatted in the same way as its logo. \LaTeX works similarly.

请注意,我们在\TeX之后使用了反斜杠。以下空格只是将命令与以下文本分开;它不会在输出中产生空格。使用反斜杠后跟一个空格会强制输出一个空格,否则会被忽略。这也适用于我们刚刚创建的命令。

Note that we used a backslash after \TeX. The following space would just separate the command from the following text; it wouldn't produce a space in the output. Using the backslash followed by a space forces the output of a space that would otherwise be ignored. That also applies to the command we just created.

现在我们将看到如何避免手动间距。

Now we will see how to avoid that manual spacing.

命令后的适当间距

Proper spacing after commands

命令后面的反斜杠很容易被遗忘。我们不能修改命令吗为了自动化?像这样的 LaTeX 不直接支持的任务可以通过使用packages来解决,它们是样式和命令的集合。

A backslash following a command could easily be forgotten. Can't we modify the command in order to automate that? Tasks like this, which aren't supported by LaTeX directly, could be solved by using packages, which are collections of styles and commands.

在这里,我们将加载xspace包;它的唯一目的是在打印输出后调整间距:

Here, we will load the xspace package; its only purpose is to adjust the spacing after printed output:

  1. 将此行插入您的序言,即在\begin{document}之前:

    \usepackage{xspace}

  2. Insert this line into your preamble, that is, before \begin{document}:

    \usepackage{xspace}

  3. \xspace命令添加到您的宏定义中:

    \newcommand{\TUG}{\TeX\ 用户组\xspace}

  4. Add the \xspace command to your macro definition:

    \newcommand{\TUG}{\TeX\ Users Group\xspace}

\usepackage{xspace}告诉 LaTeX 加载xspace包并导入它的所有定义。从现在开始,我们可以使用该包中包含的所有命令。

\usepackage{xspace} tells LaTeX to load the xspace package and to import all of its definitions. From now on, we can use all commands contained in that package.

这个包提供\xspace命令,它根据以下字符插入一个空格:

This package provides the \xspace command, which inserts a space depending on the following character:

  • 如果后面跟着一个普通的字母,那么它会在宏内容之后打印一个空格。
  • If a normal letter follows, then it will print a space after the macro content.
  • 如果后面是点、逗号、感叹号或引号,则不会插入空格。
  • If a dot, a comma, an exclamation mark, or a quotation mark follows, it won't insert a space.

这种自动化是使用xspace包的决定性原因。

That automation is the defining reason for using the xspace package.

创建更通用的命令和使用参数

Creating more universal commands and using arguments

想象一下,您的文本包含许多要以粗体显示的关键字。如果您对所有关键字使用\textbf命令,如果您稍后决定使用一个斜体,还是打字机字体?您将不得不更改每个关键字的格式。有一个更好的方法:定义你的自己的宏并仅在该宏定义中使用\textbf 。

Imagine that your text contains a lot of keywords that you want to be printed in bold. If you use the \textbf command on all the keywords, what will happen if you later decide to use an italic shape instead, or a typewriter font? You would have to change that formatting for each keyword. There's a better way: defining your own macro and using \textbf only inside that macro definition.

创建带参数的宏

Creating a macro with arguments

在本节中,我们将再次使用\newcommand,但这次我们将引入一个参数那将包含我们的关键字。例如,我们将以我们在本章中必须了解的一些术语来使用它。

In this section, we will use \newcommand again, but this time we will introduce a parameter that will contain our keyword. For the example, we will use it on some terms that we've got to know in this chapter.

让我们开始吧:

Let's get started:

  1. 在您的编辑器中键入以下代码示例。突出显示的行将是我们自己的宏定义,如下所示:

    \文档类{文章}

    \newcommand{\keyword}[1]{\textbf{#1}}

    \开始{文档}

    \keyword{Grouping} 通过花括号限制了

    \keyword{declarations} 的 \keyword{scope}。

    \end{文档}

  2. Type the following code example in your editor. The highlighted line will be our own macro definition, as shown here:

    \documentclass{article}

    \newcommand{\keyword}[1]{\textbf{#1}}

    \begin{document}

    \keyword{Grouping} by curly braces limits the

    \keyword{scope} of \keyword{declarations}.

    \end{document}

  3. 单击Typeset并观察输出中关键字的外观:
  4. Click on Typeset and observe the look of the keywords in the output:
图 2.10 – 格式化关键字

图 2.10 – 格式化关键字

Figure 2.10 – Formatting keywords

让我们看一下代码中突出显示的\new命令行。方括号中的数字1表示我们要在命令中使用的参数数量。#1将替换为第一个参数的值;#2将替换为第二个参数的值,依此类推。现在,如果要将所有关键字的外观修改为斜体,只需修改\keyword和 th的定义变革将是全球性的。

Let's look at the highlighted \newcommand line in the code. The number 1 in the square brackets marks the number of arguments that we want to use in the command. #1 will be replaced by the value of the first argument; #2 will be replaced by the value of the second argument, and so on. Now, if you want to modify the appearance of all keywords to be italic, just modify the definition of \keyword and the change will be global.

我们第一次使用\newcommand,在创建我们自己的命令部分,我们使用了它有两个参数:宏名称和宏命令。在前面的例子中,有三个参数;额外的参数已放在方括号中,这是我们标记可选参数的方式(这些参数可以给出或可以省略)。如果省略,它们将具有默认值。

The first time we used \newcommand, in the Creating our own commands section, we used it with two arguments: the macro name and the macro commands. In the previous example, there were three arguments; the additional argument has been put in square brackets, which is how we mark optional arguments (those arguments may be given or may be omitted). If omitted, they would have a default value.

以前,我们已经使用过\documentclass命令,但是我们如何自己定义一个带有可选参数的命令呢?

Previously, we've already worked with the \documentclass command, but how can we define a command with optional arguments ourselves?

创建带有可选参数的宏

Creating a macro with optional arguments

我们将下次使用\newcommand ,但是这次使用可选的格式化参数和关键字的强制参数:

We will use \newcommand another time, but this time with an optional formatting parameter and a mandatory argument for the keyword:

  1. 修改前面的示例以获得此代码:

    \文档类{文章}

    \newcommand{\keyword}[2][\bfseries]{{#1#2}}

    \开始{文档}

    \keyword{Grouping} 通过花括号限制了

    \keyword[\itshape]{declarations} 的 \keyword{scope}。

    \end{文档}

  2. Modify the previous example to get this code:

    \documentclass{article}

    \newcommand{\keyword}[2][\bfseries]{{#1#2}}

    \begin{document}

    \keyword{Grouping} by curly braces limits the

    \keyword{scope} of \keyword[\itshape]{declarations}.

    \end{document}

  3. 单击排版并查看结果:
  4. Click on Typeset and check out the result:
图 2.11 – 可选参数

图 2.11 – 可选参数

Figure 2.11 – Optional arguments

让我们再看看代码中突出显示的\new命令行。通过使用[\bfseries],我们介绍了可选参数;我们提到通过#1给它,它的默认值是\bfseries。由于我们这次使用了声明,所以我们添加了一对大括号以确保只有关键字受到声明的影响。在文档的后面,我们将[\itshape]给了\keyword,将默认格式更改为斜体。

Let's look again at the highlighted \newcommand line in the code. By using [\bfseries], we introduced an optional parameter; we refer to it by #1 and its default value is \bfseries. Since we used a declaration this time, we added a pair of braces to ensure that only the keyword is affected by the declaration. Later in the document, we gave [\itshape] to \keyword, changing the default formatting to italic.

这是\newcommand的定义:

Here's the definition of \newcommand:

\newcommand{命令}[参数][可选]{定义}

\newcommand{command}[arguments][optional]{definition}

这些是\newcommand参数的含义:

These are the meanings of the parameters to \newcommand:

  • command:新命令的名称,以反斜杠开头,后跟小写和/或大写字母,或者反斜杠后跟一个非字母符号。该名称不得已定义且不允许以\end开头。
  • command: The name of the new command, starting with a backslash followed by lowercase and/or uppercase letters, or a backslash followed by a single non-letter symbol. The name must not be already defined and is not allowed to begin with \end.
  • arguments : 一个从 1 到 9 的整数,代表新命令的参数个数。如果省略,该命令将没有参数。
  • arguments: An integer from 1 to 9, representing the number of arguments of the new command. If omitted, the command will have no arguments.
  • optional:如果存在,那么第一个参数将是可选的,这里给出默认值。否则,所有参数都是强制性的。
  • optional: If this is present, then the first of the arguments would be optional with a default value given here. Otherwise, all arguments are mandatory.
  • definition : command的每次出现都 将被definition替换, #n形式的每次出现都将被第 n 个参数替换。
  • definition: Every occurrence of command will be replaced by definition and every occurrence of the form #n will then be replaced by the nth argument.

使用\newcommand为关键字、代码片段、网址、名称、注释、信息框或不同强调的文本创建样式。我们是如何实现一致的这本书的结构?使用\newcommand定义样式是关键。我们应该在里面使用字体命令我们的宏定义,而不是在文档正文中。

Use \newcommand to create styles for keywords, code snippets, web addresses, names, notes, information boxes, or differently emphasized text. How did we achieve the consistent structure of this book? Defining styles with \newcommand is the key. We should use font commands within our macro definitions, rather than in the document body text.

一般良好做法

General good practice

尽可能多地创建自己的宏来实现逻辑结构。您将获得一致的格式,并且更改可以轻松应用于整个文档。通过定义和使用命令,您可以确保格式在整个文档中保持一致。

As often as possible, create your own macros to achieve a logical structure. You will be rewarded with consistent formatting and changes could easily be applied to the whole document. By defining and using commands, you can ensure that the formatting remains consistent throughout your whole document.

现在我们已经了解了如何格式化单词和短语,让我们看看整个段落。

Now that we have seen how to format words and phrases, let's look at whole paragraphs.

使用框来限制段落的宽度

Using boxes to limit the width of paragraphs

我们不会总是在整个文本宽度上从左到右书写文本。有时候,我们会喜欢一个段落有一个更小的宽度,例如,当我们想并排放置文本和图片时。

We won't always write text just from left to right over the complete text width. Sometimes, we'd like a paragraph to have a smaller width, for instance, when we would like to put text and a picture side by side.

在接下来的部分中,我们将了解如何在 LaTeX 中使用段落框。

In the following sections, we will look at how to work with paragraph boxes in LaTeX.

创建一个窄文本框

Creating a narrow text box

对于我们的例如,我们想在只有 3 厘米宽的文本栏中解释首字母缩略词 TUG。为此,请按照下列步骤操作:

For our example, we would like to explain the acronym TUG in a text column of only 3 cm width. To do this, follow these steps:

  1. 创建一个包含以下四行的新文档:

    \文档类{文章}

    \开始{文档}

    \parbox{3cm}{TUG 是首字母缩写词。它的意思是

    \TeX\ 用户组。}

    \end{文档}

  2. Create a new document containing these four lines:

    \documentclass{article}

    \begin{document}

    \parbox{3cm}{TUG is an acronym. It means

    \TeX\ Users Group.}

    \end{document}

  3. 单击“排版”并仔细查看间距过宽的输出:
  4. Click on Typeset and take a critical look at the output with the too-wide spacing:
图 2.12 – 窄对齐段落

图 2.12 – 窄对齐段落

Figure 2.12 – A narrow justified paragraph

我们在突出显示的代码行中使用了\parbox命令来创建一个列。\parbox命令的第一个参数将宽度设置为 3 厘米,\parbox的第二个参数包含文本。

We used the \parbox command in the highlighted code line to create a column. The first argument to the \parbox command sets the width to 3 cm, and the second argument to \parbox contains the text.

\parbox采取参数文本并格式化输出以适应指定的宽度。我们看到文本是完全合理的;然而,我们的例子显示了一个明显的问题:坚持充分的理由可能会导致文本中出现不受欢迎的大空白。可能的解决方案如下:

\parbox takes the argument text and formats the output to fit the specified width. We see that the text is fully justified; however, our example shows an obvious problem: insisting on full justification could lead to undesirable big gaps in the text. Possible solutions are as follows:

  • 我们引入连字符;首字母缩略词很容易连字符。
  • We introduce hyphenation; the word acronym could easily be hyphenated.
  • 我们总体上改进了理由。
  • We improve justification in general.
  • 我们放弃充分的理由;仅左对齐时,窄文本可能看起来更好。
  • We give up on full justification; narrow text could look better when it's only left-justified.

我们将在Breaking lines and paragraphsTurning off full justification部分检查所有这些选项。

We will check out all of these options in the Breaking lines and paragraphs and Turning off full justification sections.

但首先,让我们了解\parbox是如何工作的。

But first, let's understand how \parbox works.

制作通用段落框

Producing common paragraph boxes

通常,我们只需要一个具有一定宽度的文本框即可;偶尔,我们想要一些与周围文本的额外对齐。所以, \parbox命令的通用定义如下:

Usually, we just need a text box with a certain width; occasionally, we would like to have some additional alignment to the surrounding text. So, the common definition of the \parbox command is as follows:

\parbox[对齐方式]{宽度}{文字}

\parbox[alignment]{width}{text}

参数含义如下:

The meanings of the parameters are as follows:

  • alignment:这是垂直对齐的可选参数。状态t对齐到盒子顶线的基线;将b写在其底线的基线处对齐。默认行为是放置框,使其中心与当前文本行的中心对齐。
  • alignment: That's the optional argument for vertical alignment. State t to align at the baseline of the top line of the box; write b to align at the baseline of its bottom line. The default behavior is to place the box such that its center is in line with the center of the current text line.
  • width:这是盒子的宽度。它可以用 ISO 单位给出,例如 3 厘米、44 毫米或 2 英寸。
  • width: That's the width of the box. It can be given in ISO units, such as 3 cm, 44 mm, or 2 in.
  • text:这是您要放入该框中的文本。它应该是一小段普通文本。对于复杂或较长的内容,我们可以使用minipage环境,我们将在下一节中使用它。
  • text: That's the text that you want to put in that box. It should be a short piece of common text. For complicated or longer content, we can use the minipage environment, which we will use in the next section.

下面是对齐参数效果的演示:

Here's a demonstration of the effect of the alignment parameters:

\文档类{文章}

\documentclass{article}

\开始{文档}

\begin{document}

文本行

Text line

\quad\parbox[b]{1.8cm}{this parbox 对齐

\quad\parbox[b]{1.8cm}{this parbox is aligned

在其底线}

at its bottom line}

\quad\parbox{1.5cm}{center-aligned parbox}

\quad\parbox{1.5cm}{center-aligned parbox}

\quad\parbox[t]{2cm}{另一个在其顶行对齐的 parbox}

\quad\parbox[t]{2cm}{another parbox aligned at its top line}

\end{文档}

\end{document}

\quad命令产生一些空间;我们用它来稍微分开盒子。这是输出:

The \quad command produces some space; we used it to separate the boxes a bit. Here's the output:

图 2.13 – 对齐的段落框

图 2.13 – 对齐的段落框

Figure 2.13 – Aligned paragraph boxes

图 2.13中的输出显示了比对的工作原理。文本行是我们的基线,参考该基线,以下框分别在底部、中心或顶部对齐。

The output in Figure 2.13 shows how the alignment works. Text line is our base line, and referring to that base line, the following boxes are aligned at the bottom, the center, or the top line, respectively.

探索段落框的更多功能

Exploring further features of paragraph boxes

\parbox能够做得更多。如果您需要高级定位,这里是完整的\parbox定义:

\parbox is capable of doing even more. If you need advanced positioning, here's the complete \parbox definition:

\parbox[对齐][高度][内部对齐]{宽度}{文本}

\parbox[alignment][height][inner alignment]{width}{text}

参数含义如下:

The meanings of the parameters are as follows:

  • height:如果未给出此可选参数,则该框将只有内部文本的自然高度。如果要更改框的高度以使其变大或变小,请使用此参数。
  • height: If this optional argument isn't given, the box will have just the natural height of the text inside. Use this argument if you want to change the height of the box to make it bigger or smaller.
  • 内部对齐:如果框的高度与包含文本的自然高度不同,您可能需要调整文本位置。您可以添加以下值:

    c : 使文本在框中垂直居中

    t:将文本放在框的顶部

    b : 将文本放在底部

    s:垂直拉伸文本(如果可能)

    如果省略此参数,对齐参数将在此处用作默认值。

  • inner alignment: If the height of the box is different from the natural height of the contained text, you might want to adjust the text position. You can add the following values:

    c: Vertically centers the text in the box

    t: Places text at the top of the box

    b: Places text at its bottom

    s: Stretches the text vertically (if possible)

    If you omit this argument, the alignment argument will be used here as the default value.

以我们之前的演示示例为例尝试可选参数的效果。使用\fbox命令,有助于可视化效果;如果你写\fbox{\parbox[...]{...}{text}},完整的parbox将被框起来。

Take our previous demonstration example and try the effect of the optional arguments. Use the \fbox command, which helps to visualize the effect; if you write \fbox{\parbox[...]{...}{text}}, the complete parbox will be framed.

使用迷你页面

Using mini pages

段落boxes 适用于内部只有少量文本的盒子。对于包含大量文本的框,右大括号很容易被遗忘或忽略。minipage环境将是一个更好的选择

Paragraph boxes are suitable for boxes with only a little text inside. In the case of a box containing a large amount of text, the closing brace could easily be forgotten or overlooked. The minipage environment would then be a better choice.

在此示例中,我们将使用minipage环境而不是\parbox来获取宽度仅为 3 厘米的文本示例:

In this example, we will use the minipage environment instead of \parbox to get a sample of text with a width of just 3 cm:

  1. 修改parbox例子得到如下代码:

    \文档类{文章}

    \开始{文档}

    \begin{小页面}{3cm}

    TUG 是首字母缩写词。这意味着 \TeX\ 用户组。

    \end{小页面}

    \end{文档}

  2. Modify the parbox example to get the following code:

    \documentclass{article}

    \begin{document}

    \begin{minipage}{3cm}

    TUG is an acronym. It means \TeX\ Users Group.

    \end{minipage}

    \end{document}

  3. 单击排版并查看输出:
  4. Click on Typeset and look at the output:
图 2.14 – 一个小型页面示例

图 2.14 – 一个小型页面示例

Figure 2.14 – A minipage example

通过使用\begin{minipage},我们开始了一个“页面中的页面”。我们指定 3 厘米的宽度将是强制参数。从这一点开始,文本行的宽度将是 3 厘米;它们将自动包装并完全合理。我们用\end{minipage}结束了这个限制。之后键入的任何文本都将超出整个正文文本的宽度。

By using \begin{minipage}, we started a "page in a page." We specified that the width of 3 cm will be the mandatory argument. From this point onward, the text lines will have a width of 3 cm; they will be automatically wrapped and fully justified. We ended this restriction with \end{minipage}. Any text typed afterward would run over the complete body text width.

防止分页

Preventing page breaks

在小页面环境中永远不会有分页符,所以这是一种防止文本区域内分页符的方法。如果minipage环境中的文本不适合页面,它将移动到下一页。

There will never be a page break within a minipage environment, so that's a way to prevent page breaks within a text area. If that text within the minipage environment doesn't fit on the page, it will move to the next page.

minipage环境接受所有与\parbox具有相同含义的参数。

The minipage environment accepts all arguments similar to \parbox with the same meanings.

如果文本被包裹在一个盒子里或只是在一个普通的行中,它可能自动贴合好。但是,我们可能需要考虑手动完成断行和对齐。让我们在下一节中看看如何做到这一点。

If text is wrapped in a box or just in a normal line, it may automatically fit well. However, we may need to consider completing line breaking and justification manually. Let's see how to do this in the next sections.

断行和段落

Breaking lines and paragraphs

通常,当你在写文本时,你不需要关心换行。只需输入使用您的编辑器编辑文本,LaTeX 将使它适合行,它将处理理由。如果您想开始一个新段落,只需在继续下一段的文本之前插入一个空行。

Generally, when you're writing text, you don't need to care about the line wrapping. Just by typing the text with your editor, LaTeX will make it fit to the line and it will take care of the justification. If you want to begin a new paragraph, just insert an empty line before you continue with your text for the next paragraph.

现在我们将了解如何控制换行。首先,我们将了解如何改进自动断字,其次,我们将学习直接插入分隔符的命令。

Now we will find out how to control the line wrapping. First, we will see how to improve the automatic hyphenation, and second, we will learn commands to insert breaks directly.

改进断字

Improving hyphenation

如果你查看较长的文档,您会注意到 LaTeX 如何完全对齐文本以及如何在行上均匀分布单词之间的间距,这一点非常出色。如有必要,LaTeX 会分割单词并在行尾放置连字符,以便更好地断行。LaTeX 已经使用了很好的算法来对单词进行断字,但它可能会找不到可接受的单词划分方式。前面的例子指出了这个问题:打破单词首字母缩略词会改善输出,但 LaTeX 不知道在哪里划分它。我们将找出解决方法。

If you look at longer documents, you will notice that it's outstanding how the text is fully justified by LaTeX and how the spacing between words is evenly distributed on the lines. If necessary, LaTeX will divide words and put hyphens at the end of the line in order to break the lines in a better way. LaTeX already uses very good algorithms to hyphenate words, but it may happen that it can't find an acceptable way to divide a word. The previous example pointed out this problem: breaking the word acronym would improve the output, but LaTeX does not know where to divide it. We shall find out how to solve that.

无论理由多么充分,非常狭窄的栏中的文本都极难证明其合理性。为了实现完全对齐,LaTeX 在单词之间插入了很大的空隙。

No matter how good the justification is, text in very narrow columns is extremely hard to justify. To achieve full justification, LaTeX inserts big gaps between the words.

在里面下面的例子,我们将告诉 LaTeX 一个单词如何划分,让 LaTeX 在段落对齐方面有更大的灵活性:

In the following example, we will tell LaTeX how a word could be divided, to give LaTeX more flexibility for paragraph justification:

  1. 将以下行插入到上一个示例的序言中:

    \连字符{首字母缩略词}

  2. Insert the following line into the preamble of the previous example:

    \hyphenation{acro-nym}

  3. 单击排版并查看输出:
  4. Click on Typeset and look at the output:
图 2.15 – 改进连字符的段落

图 2.15 – 改进连字符的段落

Figure 2.15 – A paragraph with improved hyphenation

我们已经告诉 LaTeX 单词acronym可能在acronym之间有一个分界点。这意味着可以在行尾的acro之后放置一个连字符,而nym向下移动到下一行。

We've told LaTeX that the word acronym may have a division point between acro and nym. That means a hyphen might be placed after acro at the end of the line and nym moves down to the following line.

\hyphenation命令告诉 LaTeX 单词的分割点在哪里。它的参数可能包含几个由空格分隔的单词。对于每个词,我们可以指出几个点。例如,我们可以通过更多的划分点和更多的单词变体来扩展论证,如下所示:

The \hyphenation command tells LaTeX where the division points of a word may be. Its argument may contain several words separated by spaces. For each word, we can indicate several points. For instance, we could extend the argument by more division points and more word variants, like this:

\连字符{ac-ro-nym ac-ro-nym-ic a-cro-nym-i-cal-ly}

\hyphenation{ac-ro-nym ac-ro-nym-ic a-cro-nym-i-cal-ly}

您还可以通过插入反斜杠后跟连字符来指示正文中的分割点,例如ac\-ro\-nym。但是通过在序言中使用\hyphenation命令,您将在那里收集所有规则,并且它们将被一致地使用;所以,特别是在 LaTeX 的自动化失败的罕见情况下使用它。

You could also indicate division points in the body text by inserting a backslash followed by a hyphen, such as ac\-ro\-nym. But by using the \hyphenation command in the preamble, you would collect all rules there and they will be used consistently; so, use it especially in the rare cases where LaTeX's automation fails.

防止断字

Preventing hyphenation

如果你想要完全防止某个单词的连字,有两种可能的方法:

If you want to prevent the hyphenation of a certain word at all, there are two possible ways:

  • 通过在没有任何分割点的\hyphenation参数中使用它在序言中声明它,例如\hyphenation{indivisible}
  • Declare it in the preamble by using it in the \hyphenation argument without any division points, such as \hyphenation{indivisible}.
  • 使用\mbox命令将其保护在文本中:以下单词是 \mbox{indivisible}
  • Protect it inside the text using the \mbox command: The following word is \mbox{indivisible}.

加载hyphenat包给了我们两个更多的选择:

Loading the hyphenat package gives us two more choices:

  • \usepackage[none]{hyphenat}防止在整个文档中使用连字符。
  • \usepackage[none]{hyphenat} prevents hyphenation throughout the document.
  • \usepackage[htt]{hyphenat}为打字机文本启用连字符;否则,默认情况下不会将这些等宽单词连字符。
  • \usepackage[htt]{hyphenat} enables hyphenation for typewriter text; otherwise, such monospaced words won't be hyphenated by default.

\usepackage的这些可选参数称为包选项。他们配置包的行为。提到的选项可以组合,用逗号分隔。即使您不使用none选项,您也可以使用\nohyphens{text}命令禁用短文本的断字。如果您想从中受益,请尝试这些功能。软件包文档解释了您有时可能需要的更多功能,例如数字和标点符号等特殊字符后的连字符。

These optional arguments to \usepackage are called package options. They configure the behavior of a package. The mentioned options may be combined, separated by commas. Even if you don't use the none option, you can disable hyphenation for short pieces of text using the \nohyphens{text} command. Try out these features if you want to benefit from them. The package documentation explains more features that you may sometimes need, such as hyphenation after special characters such as numerals and punctuation.

改进理由

Improving the justification

今天最流行的TeX 编译器是pdfTeX,它直接产生 PDF 输出。什么时候Hàn Thế Thành 开发了 pdfTeX,他用微型排版功能扩展了 TeX。当我们直接排版为 PDF 时,我们实际上使用pdfLaTeX ,我们可以通过使用microtype包从新功能中受益。

Today's most popular TeX compiler is pdfTeX, which directly produces PDF output. When Hàn Thế Thành developed pdfTeX, he extended TeX with micro-typographic capabilities. When we typeset directly to a PDF, we're actually using pdfLaTeX and we can benefit from the new features by using the microtype package.

让我们通过加载microtype包来改进我们之前的示例:

Let's improve our previous example by loading the microtype package:

  1. 将以下行插入到上一个示例的序言中:

    \usepackage{微型}

  2. Insert the following line into the preamble of the previous example:

    \usepackage{microtype}

  3. 单击排版并查看输出:
  4. Click on Typeset and look at the output:
图 2.16 – 一个有更好理由的段落

图 2.16 – 一个有更好理由的段落

Figure 2.16 – A paragraph with better justification

我们加载了microtype包,没有任何选项,依赖于它的默认行为。它引入了字体扩展来调整对齐方式并使用悬挂标点符号以改善边缘的光学外观。这可能会减少连字符的需要,并避免在单词之间出现较大的间隙以实现完全对齐。您已经看到它对窄栏的影响,所以想象一下宽文本的改进——记住这一点,稍后再试一试!

We have loaded the microtype package without any options, relying on its default behavior. It introduces font expansion to tweak the justification and uses hanging punctuation to improve the optical appearance of the margins. This may reduce the need for hyphenation and avoids having large gaps between words for achieving full justification. You've seen its effect on a narrow column, so imagine the improvement on wide text—keep that in mind and try it out later!

尽管微类型为高级排字机提供了强大的功能和选项,但我们通常只需加载它即可从中受益。如果您想深入研究它,这里有大量的包文档。microtype可以很好地调整,但它不是万灵药;必要时,我们仍应注意适当的断字。

Though microtype provides powerful features and options for the advanced typesetter, we usually won't need to do more than just load it to benefit from it. There's extensive package documentation if you want to study it in depth. microtype does nice tweaking but it's not a cure-all; we should still take care of proper hyphenation when necessary.

手动断线

Breaking lines manually

我们可能会选择自己结束一条线,而不是自动化。在这里,我们将了解几个具有不同效果的命令来结束一行。

We might choose to end a line ourselves, overriding the automation. Here, we will learn about several commands with different effects for ending a line.

我们将键入埃德加·爱伦·坡 (Edgar Allan Poe) 的一首著名诗歌的开头。由于诗人指定了诗句必须结束的地方,我们将在那里插入换行符。

We will type the beginning of a famous poem by Edgar Allan Poe. As the poet has specified where a verse has to end, we shall insert line breaks there.

所以,让我们写下这首诗的开头:

So, let's write up the beginning of the poem:

  1. 创建包含这些行的文档:

    \文档类{文章}

    \开始{文档}

    \noindent\emph{安娜贝尔·李}\\

    很多很多年前,\\

    在海边的王国里,\\

    那里住着一个你可能认识的少女\\

    以安娜贝尔李的名义

    \end{文档}

  2. Create a document containing these lines:

    \documentclass{article}

    \begin{document}

    \noindent\emph{Annabel Lee}\\

    It was many and many a year ago,\\

    In a kingdom by the sea,\\

    That a maiden there lived whom you may know\\

    By the name of Annabel Lee

    \end{document}

  3. 单击排版并查看输出:
  4. Click on Typeset and view the output:
图 2.17 – 手动打断的线

图 2.17 – 手动打断的线

Figure 2.17 – Manually broken lines

非常短的\\命令结束了一行,而下面的文本被移到了下一行。那不一样从段落中断开始,因为我们仍在使用同一段落。\newline命令也有同样的效果。

The very short \\ command ended a line, while the following text was moved to the next line. That's different from a paragraph break as we're still using the same paragraph. The \newline command also has the same effect.

\noindent命令禁止段落缩进。否则,段落中的第一行将默认缩进。缩进实际上是为了在视觉上分隔段落。我们手动抑制了缩进,因为没有节标题。标题后,默认情况下没有缩进。您通常不需要\noindent命令。对于一般删除段落缩进并将其替换为垂直段落间距,请加载parskip包。您可以在图 2.23和相应的代码中看到这一点。

The \noindent command suppresses the paragraph indentation. Otherwise, the first line in the paragraph would be indented by default. Indenting is actually intended for visually separating paragraphs. We suppressed indentation manually because there is no section heading. After headings, there's no indentation by default. You normally don't need the \noindent command. For generally removing paragraph indentation and replacing it with vertical inter-paragraph spacing, load the parskip package. You can see this in Figure 2.23 and the corresponding code.

注意虽然我们插入了行尾,但它仍然是一个段落。因此,换行符不会导致段落缩进,因为它在逻辑上是同一段落。

Note that although we inserted line endings, it is still a single paragraph. So, a line break doesn't cause a paragraph indentation since it's logically the same paragraph.

探索换行选项

Exploring line breaking options

\\命令_使用以下语法理解可选参数:

The \\ command understands optional arguments with the following syntax:

  • \\[value]根据value在中断后插入额外的垂直空间,例如\\[3mm]
  • \\[value] inserts additional vertical space after the break depending on the value, such as \\[3mm].
  • \\*[value]是前一个参数的变体,但可以防止在下一行文本之前出现分页符。
  • \\*[value] is a variation of the previous argument but prevents a page break before the next line of text.

还有另一个名为\linebreak 的命令告诉 LaTeX 结束该行但保持完整的对齐方式,因此单词之间的空间将被拉伸以达到右边距。这可能会导致不愉快的间隙——这就是为什么很少使用该命令的原因。

There's another command called \linebreak that tells LaTeX to end the line but to keep the full justification, therefore the space between the words would be stretched to reach the right margin. This could cause unpleasant gaps—that's why that command is rarely used.

\linebreak[number]可用于调整换行符。如果number0,则允许换行;1表示需要;23标记更坚持的请求;4将强制执行。如果没有给出数字,后者是默认行为。

\linebreak[number] can be used to tweak the line break. If number is 0, a line break is allowed; 1 means it's desired; 2 and 3 mark more insistent requests; 4 will enforce it. The latter is the default behavior if no number is given.

你可以试试出这些数字;例如,将我们的诗歌示例的标题更改为以下内容:

You may try out these numbers; for example, change the heading of our poem example to the following:

\emph{安娜贝尔·李}\\[3mm]

\emph{Annabel Lee}\\[3mm]

这会在我们的标题和诗歌片段之间插入一个额外的 3 毫米空间。继续使用选项来查看它们的效果。

That inserts an additional 3 mm space between our heading and the poem fragment. Continue playing with the options to see their effects.

防止换行

Preventing line breaks

\linebreak命令有一个直接的对应命令:\nolinebreak。此命令防止在当前位置换行。

The \linebreak command has a direct counterpart: \nolinebreak. This command prevents a line break at the current position.

喜欢它的对应的,它需要一个可选参数。如果你写\nolinebreak[0],你建议不要在那里断行。使用12甚至3会使请求更强,而\nolinebreak[4]会完全禁止它。如果您不提供论据,将假定后一种选择。

Like its counterpart, it takes an optional argument. If you write \nolinebreak[0], you recommend not to break the line there. Using 1, 2, or even 3 makes the request stronger and \nolinebreak[4] forbids it completely. The latter option will be presumed if you don't provide an argument.

已经提到的\mbox{text}命令不仅会禁用单词的连字符,还会防止整个文本换行。

The already mentioned \mbox{text} command not only disables the hyphenation of a word but will also prevent a line break for the complete text.

如果有意义,LaTeX 会在单词之间的空格处换行。~符号代表不允许中断的字间空间;如果你写Dr.~Watson , Dr.的标题永远不会孤单地出现在一行的末尾。

LaTeX will break lines at spaces between words if meaningful. The ~ symbol stands for an interword space where no break is allowed; if you write Dr.~Watson, the title Dr. would never stand lonely at the end of a line.

默认情况下,文本是完全对齐的。这意味着如果需要,线条会拉伸到右边距。这可能会导致拉伸行中的单词之间出现不需要的间隙。如果我们愿意,让我们看看如何禁用它。

By default, the text is fully justified. That means lines are stretched to the right margin if needed. This may result in undesirable gaps between words in a stretched line. Let's see how to disable it if we want to.

关闭完全对齐

Turning off full justification

虽然如果使用完全对齐,您的文本通常看起来很好,但有时可能不是最佳选择。例如,完整的理由可能会令人不快,如果文本行很短;在这种情况下,仅证明左侧就足够了。我们将看到如何将其付诸实践,以及如何右对齐和如何获得居中线。

Though commonly your text will look fine if full justification is used, there may be occasions when it's not optimum. For instance, full justification could be displeasing if the text lines are short; in such a case, it could be sufficient to justify only to the left side. We shall see how to put this into practice, plus how to right-justify and how to get centered lines.

创建右对齐文本

Creating ragged-right text

记住第一个 parbox 的例子,它是完全合理的,但两者之间有很大的差距的话?在这个例子中,我们将放弃对右边的证明以避免这样的差距:

Remember the first parbox example, which was fully justified but had those big gaps between the words? In this example, we shall give up justification to the right side to avoid such gaps:

  1. 创建一个包含这些行的新文档:

    \文档类{文章}

    \开始{文档}

    \parbox{3cm}{\raggedright

        TUG 是首字母缩写词。这意味着 \TeX\ 用户组。}

    \end{文档}

  2. Create a new document containing these lines:

    \documentclass{article}

    \begin{document}

    \parbox{3cm}{\raggedright

        TUG is an acronym. It means \TeX\ Users Group.}

    \end{document}

  3. 单击排版并查看输出:
  4. Click on Typeset and look at the output:
图 2.18 – 左对齐文本

图 2.18 – 左对齐文本

Figure 2.18 – Left-justified text

我们插入了\raggedright声明。从这一点开始,文本将变得不规则。换句话说,文本将被移动到左边距——“flushed-left”。不会有断字。

We inserted the \raggedright declaration. From this point onward, the text will be ragged-right. In other words, the text will be moved to the left margin—"flushed-left." There won't be hyphenation.

因为我们在盒子内使用了这个声明,所以它只在那里有效,就像在内部环境中一样。在框之后,文本将再次完全对齐。

Because we used this declaration inside a box, it's only valid there, like inside environments. After the box, the text will be fully justified again.

如果我们想要整个文档是 ragged-right,我们只需要在我们的序言中使用\raggedright 。

If we want the whole document to be ragged-right, we just need to use \raggedright in our preamble.

创建左对齐文本

Creating ragged-left text

有时我们可能想要达到相反的效果:刷新文本到右边距。我们可以通过插入\raggedleft声明来类似地做到这一点。您可以通过插入\\来控制断行的位置。

There might be occasions when we would like to achieve the opposite effect: flushing the text to the right margin. We can do this similarly by inserting the \raggedleft declaration. You're able to control where lines are broken by inserting \\.

居中文本

Centering text

文字还可以在页面中间水平居中。我们将尝试使用一些示例行居中。

Text can also be horizontally centered in the middle of the page. We will try centering with a few example lines.

我们将为我们的文档手动创建一个漂亮的标题;它应该包含标题、作者和日期,所有这些都将居中:

We will manually create a nice-looking title for our document; it should contain the title, the author, and the date, all of which will be centered:

  1. 编写包含此代码的文档:

    \文档类{文章}

    \pagestyle{空}

    \开始{文档}

    {\定心

        \huge\bfseries 居中文本 \\

        \Large\normalfont 是我写的\\

        \normalsize\今天

    }

    \end{文档}

  2. Write a document containing this code:

    \documentclass{article}

    \pagestyle{empty}

    \begin{document}

    {\centering

        \huge\bfseries Centered text \\

        \Large\normalfont written by me \\

        \normalsize\today

    }

    \end{document}

  3. 单击排版以查看输出:
  4. Click on Typeset to see the output:
图 2.19 – 居中文本

图 2.19 – 居中文本

Figure 2.19 – Centered text

因为只有标题要居中,所以我们开了一个group来限制居中。使用\centering声明,该组的剩余文本将水平对齐到中心。我们还插入了一个空行的段落分隔符;这是推荐的在结束小组之前执行此操作以将我们的居中应用到完整包含的段落。通过使用右大括号,我们结束了该组。如果您在右大括号之后补充一些文本,它将正常排版,而不是居中。

Because only the title should be centered, we opened a group to limit the centering. With the \centering declaration, the remaining text of this group will be horizontally aligned to the center. We also inserted a paragraph break with an empty line; it's recommended to do this before ending the group to apply our centering to the fully contained paragraph. By using the closing brace, we ended the group. If you complement some text after the closing brace, it will be typeset normally, not centered.

\centering通常在插入图片或表格时使用,或者在标题页上进一步使用,有时用于标题,而是作为逻辑命令定义的一部分。

\centering is commonly used when pictures or tables are inserted, or further on title pages and sometimes for headings, but rather as part of logical command definitions.

使用环境进行辩护

Using environments for justification

有一个预定义的center环境,可以将文本居中并同时将其打印在显示的段落中。

There's a predefined center environment that centers text and prints it in a displayed paragraph at the same time.

让我们测试一下。我们将重复使用 Edgar Allen Poe 诗的片段。这一次,我们将集中所有的经文:

Let's test it. We will reuse the fragment of the Edgar Allen Poe poem. This time, we shall center all verses:

  1. 开始一个新文档:

    \文档类{文章}

  2. Start a new document:

    \documentclass{article}

  3. 现在,让我们加载url包,这样我们也可以在最后打印一个超链接:

    \usepackage{url}

  4. Now, let's load the url package so that we can also print a hyperlink at the end:

    \usepackage{url}

  5. 以一些文本开始文档:

    \开始{文档}

    \noindent 这是一首诗的开头

    埃德加爱伦坡:

  6. Begin the document with some text:

    \begin{document}

    \noindent This is the beginning of a poem

    by Edgar Allan Poe:

  7. 现在,在中心环境中编写文本:

    \开始{中心}

        \emph{安娜贝尔·李}

    \结束{中心}

  8. Now, write text in a center environment:

    \begin{center}

        \emph{Annabel Lee}

    \end{center}

  9. 再次,为诗的正文写下文字:

    \开始{中心}

        很多很多年前,\\

        在海边的王国里,\\

        那里住着一个你可能认识的少女\\

        以安娜贝尔李的名义

    \结束{中心}

  10. Again, write text for the body of the poem:

    \begin{center}

        It was many and many a year ago,\\

        In a kingdom by the sea,\\

        That a maiden there lived whom you may know\\

        By the name of Annabel Lee

    \end{center}

  11. 添加一些文本,包括指向互联网上这首诗的 URL,然后完成:

    完整的诗可以继续阅读

    \url{http://www.online-literature.com/poe/576/}。

    \end{文档}

  12. Add some text, including a URL pointing to the poem on the internet, and finish:

    The complete poem can be read on

    \url{http://www.online-literature.com/poe/576/}.

    \end{document}

  13. 单击排版并查看输出:
  14. Click on Typeset and see the output:
图 2.20 – 文本中居中的诗

图 2.20 – 文本中居中的诗

Figure 2.20 – A centered poem within text

我们再次从\noindent开始,避免段落缩进。\begin{center}启动了center环境,它开始了一个新段落,为前面的文本留出一些空间。\end{center}结束了这个环境。我们第二次使用了 center 环境,我们在其中插入\\来结束这些诗句。center环境结束后,紧接着是一些空格,下一段从左边距开始。

We began with \noindent again, avoiding the paragraph indentation. \begin{center} started the center environment, which begins a new paragraph, leaving some space for the preceding text. \end{center} ended this environment. We used the center environment a second time, where we inserted \\ to end the verses. After the center environment ended, some space followed, and the next paragraph began at the left margin.

没有只有一个用于居中的环境。右对齐文本的相应环境称为flushleft;也就是说,环境中的所有内容都被推到左边,右边参差不齐,同样,对于参差不齐的左侧文本,它是flushright

There's not only an environment for centering. The corresponding environment for ragged-right text is called flushleft; that is, everything within the environment is pushed to the left and ragged at the right side, and, similarly, for ragged-left text, it's flushright.

如前所述,居中是强调某些文本的一种方式。另一种方法是缩进一点,并在文本前后添加一些垂直空间。这是显示报价单的常用方式。让我们看看如何做到这一点。

Centering, as previously, is one way to emphasize some text. Another way is to indent it a bit and to add some vertical space before and after the text. This is a common way to display a quotation. Let's see how to do that.

显示报价

Displaying quotes

假设您的文本包含另一位作者的引文。如果只是这样,可能很难阅读嵌入到您的文本中。提高可读性的一种常见方法是通过缩进两个边距来关闭文本。为此,我们将在示例中引用著名物理学家的想法:

Imagine your text contains a quotation from another author. It might be hard to read if it's just embedded in your text. A common way to improve the readability is setting the text off by indenting both margins. To do this, we will quote thoughts of famous physicists in our example:

  1. 使用一些介绍性文本创建一个新文档:

    \文档类{文章}

    \开始{文档}

    \noindent Niels Bohr 说:``专家就是一个人

    谁犯了所有可以犯的错误

    一个非常狭窄的领域。

    爱因斯坦说:

  2. Create a new document with some introductory text:

    \documentclass{article}

    \begin{document}

    \noindent Niels Bohr said: ``An expert is a person

    who has made all the mistakes that can be made in

    a very narrow field.''

    Albert Einstein said:

  3. 显示报价:

    \开始{引用}

        从未犯过错误的人永远不会

        尝试任何新事物。

    \结束{引用}

  4. Display the quote:

    \begin{quote}

        Anyone who has never made a mistake has never

        tried anything new.

    \end{quote}

  5. 添加一些更多正文,并完成:

    错误是不可避免的。所以,让我们勇敢一点

    尝试新事物。

    \end{文档}

  6. Add some more body text, and finish:

    Errors are inevitable. So, let's be brave

    trying something new.

    \end{document}

  7. 点击排版查看结果:
  8. Click on Typeset to see the result:
图 2.21 – 报价

图 2.21 – 报价

Figure 2.21 – A quote

首先,我们引用了行内引用,也就是段落中的文本流内。`产生左引号标记,也称为反引号'提供右引号。获得双倍引号,我们只是输入了两个这样的符号。我们称之为内联引用

Firstly, we quoted inline, that is, within the text flow in the paragraph. ` produces a left quotation mark, also called a backtick, and ' provides a right quotation mark. To get double quotes, we just typed two such symbols. We call this inline quoting.

然后,我们使用报价环境显示与周围文本分开的引文。我们没有为它开始一个新的段落,因为引文在它自己的段落中已经有点偏离了。这就是所谓的显示引用

Then, we used the quote environment to display a quotation separated from the surrounding text. We did not begin a new paragraph for it, because the quotation is already set a bit off in its own paragraph. That's called displayed quoting.

引用较长的文本

Quoting longer text

写短报价时,报价环境看起来非常好。但是当你想要引用包含多个段落的文本,您可能希望使用与周围文本相同的段落缩进。报价环境将为您完成这项工作

When writing short quotations, the quote environment looks very good. But when you would like to quote text containing several paragraphs, you might wish to have the same paragraph indentation as in your surrounding text. The quotation environment will do this for you.

让我们引用在 CTAN 的网页上找到的 TeX 和 LaTeX 的一些好处:

Let's quote some of the benefits of TeX and LaTeX found on a web page on CTAN:

  1. 开始一个新文档并添加以下文本:

    \文档类{文章}

    \usepackage{url}

    \开始{文档}

    CTAN 团队的作者列出了十个很好的理由

    用于使用 \TeX。其中包括:

    \begin{报价单}

      \TeX\ 有最好的输出。你以什么结束,

      页面上的符号既可用又漂亮,

      作为非专业人士可以制作。

      \TeX\ 知道排版。作为那些纯文本样本

      显示,TeX 有更复杂的排版

      算法,例如用于制作段落的算法

      和连字符。

      \TeX\ 很快。在今天的机器上 \TeX\ 非常快。

      内存和磁盘空间也很容易。

      \TeX\ 是稳定的。它用途广泛,历史悠久

      历史。经过数百万用户的测试,

      在苛刻的输入。

      它永远不会吃掉你的文件。绝不。

    \end{引用}

    原文可见于

    \url{https://www.ctan.org/what_is_tex.html}。

    \end{文档}

  2. Start a new document and add this text:

    \documentclass{article}

    \usepackage{url}

    \begin{document}

    The authors of the CTAN team listed ten good reasons

    for using \TeX. Among them are:

    \begin{quotation}

      \TeX\ has the best output. What you end with,

      the symbols on the page, is as useable, and beautiful,

      as a non-professional can produce.

      \TeX\ knows typesetting. As those plain text samples

      show, TeX's has more sophisticated typographical

      algorithms such as those for making paragraphs

      and for hyphenating.

      \TeX\ is fast. On today's machines \TeX\ is very fast.

      It is easy on memory and disk space, too.

      \TeX\ is stable. It is in wide use, with a long

      history. It has been tested by millions of users,

      on demanding input.

      It will never eat your document. Never.

    \end{quotation}

    The original text can be found on

    \url{https://www.ctan.org/what_is_tex.html}.

    \end{document}

  3. 单击排版查看输出:
  4. Click on Typeset and look at the output:
图 2.22 – 一段很长的引用文本

图 2.22 – 一段很长的引用文本

Figure 2.22 – A long section of quoted text

这一次,我们使用引用环境来显示一些段落。与普通文本一样,段落之间用空行分隔;就像我们所有的正文一样,它们在开头是左缩进的。

This time, we used the quotation environment to display some paragraphs. As in normal text, blank lines separate the paragraphs; they are left-indented at their beginning just like in all our body text.

但是如果我们不喜欢那个段落缩进?让我们看看替代方案。

But what if we don't like that paragraph indentation? Let's check out an alternative.

在此示例中,我们希望避免段落缩进,而是将段落分隔开一些垂直间距。作为填充文本,我们将使用前面示例中有关引用的几句话,如下所示:

In this example, we want to avoid paragraph indentation and instead, we shall separate the paragraphs with some vertical spacing. As filler text, we will use a few sentences of the previous example about quoting, as shown here:

  1. 使用以下代码创建一个小文档(确保包含突出显示的代码):

    \文档类{文章}

    \usepackage{parskip}

    \usepackage{url}

    \开始{文档}

    CTAN 团队的作者列出了十个很好的理由

    用于使用 \TeX。其中包括:

    \TeX\ 有最好的输出。你以什么结束,

    页面上的符号既可用又漂亮,

    作为非专业人士可以产生\ldots

    原文可见于

    \url{https://www.ctan.org/what_is_tex.html}。

    \end{文档}

  2. Create a small document with the following code (make sure the highlighted code is included):

    \documentclass{article}

    \usepackage{parskip}

    \usepackage{url}

    \begin{document}

    The authors of the CTAN team listed ten good reasons

    for using \TeX. Among them are:

    \TeX\ has the best output. What you end with,

    the symbols on the page, is as useable, and beautiful,

    as a non-professional can produce\ldots

    The original text can be found on

    \url{https://www.ctan.org/what_is_tex.html}.

    \end{document}

  3. 点击排版,看效果:
  4. Click on Typeset and see the effect:
图 2.23 – 段落之间的垂直间距

图 2.23 – 段落之间的垂直间距

Figure 2.23 – Vertical spacing between paragraphs

在这里,我们加载了parskip包——它的唯一目的是删除段落缩进完全地。同时,这个包引入了段落之间的跳转。但是这个包不影响引用环境的定义;您仍然可以使用报价环境。

Here, we loaded the parskip package—its only purpose is to remove the paragraph indentation completely. At the same time, this package introduces a skip between paragraphs. But this package doesn't affect the definition of the quotation environment; you still could use the quote environment.

可视化分段符

Visualizing paragraph breaks

为了区分段落,有两种常用的方法。一是缩进每一段的开头;这是默认的 LaTeX 样式。另一种方法是在段落之间插入垂直空间,同时省略缩进,这适用于缩进会花费太多宽度的窄列。

In order to distinguish paragraphs, there are two common ways. One is to indent the beginning of each paragraph; this is the default LaTeX style. The other way is to insert vertical space between paragraphs while omitting the indentation, which is suitable for narrow columns where indenting would cost too much width.

概括

Summary

在本章中,我们探讨了编辑、排列和格式化文本的基础知识。具体来说,我们介绍了修改文本的字体和样式,使用带有强制和可选参数的命令和声明,以及定义我们自己的命令。我们还学习了如何格式化段落——包括左对齐、右对齐或完全对齐——我们还学习了引用。

In this chapter, we explored the basics of editing, arranging, and formatting text. Specifically, we covered modifying fonts and styles of text, using commands and declarations with mandatory and optional arguments, and defining our own commands. We also learned how to format a paragraph—including left, right, or fully justified—and we learned about quoting.

请记住,尽管我们在探索它们时直接在文本中使用了格式化命令,但最好在序言中的命令定义中使用它们,以便将来轻松更改。随着本书的进展,您将了解更多有用的命令和包,它们可以改进您以前编写的命令。

Keep in mind that even though we used formatting commands directly in the text while exploring them, it is better to use them inside command definitions in the preamble to allow easy changes for the future. As you progress through the book, you will get to know further useful commands and packages that could improve your previously written commands.

现在我们已经了解了文本的详细格式设置,我们准备进入下一章,该章涉及整个页面的格式设置和布局,包括边距大小、页眉和页脚。

Now that we've learned about the detailed formatting of text, we're ready to enter the next chapter, which deals with the formatting and layout of whole pages, including margin sizes, headers, and footers.

第 3 章:设计页面

Chapter 3: Designing Pages

在上一章之后,格式化文本对我们来说应该很容易了。所以,让我们翻到整页!

After the previous chapter, formatting text should be easy for us. So, let's turn to whole pages!

在本章中,我们将学习如何按章节构建文档,以及如何修改页边距、页面方向、页眉和页脚等一般外观。这使您可以控制整个文档设计。

In this chapter, we will learn how to structure a document in chapters and sections, and how to modify the general appearance such as the margins, the page orientation, headers, and footers. This gives you control over the whole document design.

我们将了解以下内容:

We will learn about the following:

  • 创建一本书的章节
  • Creating a book with chapters
  • 定义边距
  • Defining the margins
  • 使用类选项
  • Using class options
  • 设计页眉和页脚
  • Designing headers and footers
  • 使用脚注
  • Using footnotes
  • 断页
  • Breaking pages
  • 放大页面
  • Enlarging a page
  • 更改行距
  • Changing the line spacing
  • 创建目录
  • Creating a table of contents

通过这方面的工作,我们将对类和包有更深入的了解。

By working on this, we shall gain a deeper insight into classes and packages.

我们将从编写一个跨越数页的示例文档开始。这将是我们修改的测试对象。

We will start by writing an example document spanning over several pages. This will be our test object for our modifications.

技术要求

Technical requirements

您需要在您的计算机上安装 LaTeX,或者您可以使用 Overleaf。您可以在本书的网页上在线编辑和编译所有示例:https://latexguide.org/chapter-03

You need either a LaTeX installation on your computer, or you can use Overleaf. You can edit and compile all examples online on the book's web page: https://latexguide.org/chapter-03.

该代码也可在 GitHub 上获得:https ://github.com/PacktPublishing/LaTeX-Beginner-s-Guide-2nd-Edition-/tree/main/Chapter_03_-_Designing_Pages 。

The code is also available on GitHub: https://github.com/PacktPublishing/LaTeX-Beginner-s-Guide-2nd-Edition-/tree/main/Chapter_03_-_Designing_Pages.

在本章中,我们将使用以下 LaTeX 包:babelblindtextfancyhdrgeometrysetspace。如果你不在线工作,如果你没有完整的 LaTeX 安装,请确保你已经安装了它们。我们还将讨论bigfootendnotesfootmisclipsummanyfootmulticolsafefnmarkscrlayer-scrpage包,您可以选择使用它们。

In this chapter, we will use the following LaTeX packages: babel, blindtext, fancyhdr, geometry, and setspace. If you don't work online, make sure you have them installed if you don't have a full LaTeX installation. We'll also talk about the packages bigfoot, endnotes, footmisc, lipsum, manyfoot, multicol, safefnmark, and scrlayer-scrpage, which you may optionally use.

您可以在https://ctan.org/pkg/<packagename>找到关于 CTAN 的包信息,在https://texdoc.org/pkg/<packagename>找到文档。

You can find package information on CTAN at https://ctan.org/pkg/<packagename>, and documentation at https://texdoc.org/pkg/<packagename>.

创建一本书的章节

Creating a book with chapters

我们将开始写一本书。首先,我们将选择一个类,并使用一些填充文本来制定页面布局。让我们看看怎么做:

We will start to write a book. First, we shall choose a class, and use some filler text to work out the page layout. Let's see how to do it:

  1. 创建一个新文档,并输入以下行作为我们的序言:

    \documentclass[a4paper,12pt]{book}

    \usepackage[english]{babel}

    \usepackage{盲文}

  2. Create a new document, and enter the following lines as our preamble:

    \documentclass[a4paper,12pt]{book}

    \usepackage[english]{babel}

    \usepackage{blindtext}

  3. 继续编写包含章节标题、章节和小节标题以及一些填充文本的文档正文:

    \开始{文档}

    \chapter{探索页面布局}

    在本章中,我们将学习页面的布局。

    \section{一些填充文字}

    \盲文

    \section{更多填充文本}

    更多虚拟文本将随之而来。

    \subsection{大量填充文字}

    \盲文[10]

    \end{文档}

  4. Proceed with writing the document body containing a chapter heading, section and subsection headings, and some filler text:

    \begin{document}

    \chapter{Exploring the page layout}

    In this chapter we will study the layout of pages.

    \section{Some filler text}

    \blindtext

    \section{A lot more filler text}

    More dummy text will follow.

    \subsection{Plenty of filler text}

    \blindtext[10]

    \end{document}

  5. 编译它通过点击Typeset。先看第一页:
  6. Compile it by clicking on Typeset. Look at the first page:
图 3.1 – 示例页面

图 3.1 – 示例页面

Figure 3.1 – An example page

我们选择了文档类book。顾名思义,此类适用于书籍类文档。书籍通常是双面的,由章节组成。默认情况下,这很常见,章节从右侧页面开始,页码为奇数。如果有必要实现这一点,LaTeX 会插入一个空白的左侧偶数页,以便下一章可以从下一个右侧页面开始。

We have chosen the document class book. As the name implies, this class is suitable for book-like documents. Books are commonly two-sided and consist of chapters. By default, and this is very common, chapters start on right-hand pages, which have odd page numbers. If it's necessary to achieve that, LaTeX inserts a blank left-hand even-numbered page so that the next chapter can start on the following right-hand page.

此外,书籍的封面可能有一个或多个标题页,背面有参考书目、索引等。book支持所有这些。

Furthermore, books may have front matter with one or more title pages and back matter with a bibliography, index, and so on. The book class supports all of this.

我们使用了选项a4paper,因此文档的格式将适合 A4 纸。对于美国信纸尺寸,我们将改用信纸选项。

We used the option a4paper so the document would be formatted to fit on A4 paper. For the US letter paper size, we would use the letterpaper option instead.

文档类选项12pt告诉 LaTeX 使用 12 pt 的基本字体大小。

The document class option 12pt told LaTeX to use a base font size of 12 pt.

我们加载了babel包。该软件包为多种语言提供排版支持工具,例如所选语言的正确连字符规则和隐含术语的翻译。例如,我们在babel中使用了english选项,并在我们的章节标题中获得了第 1 章。如果我们选择法语而不是英语,我们将在标题中看到第 1 章。

We loaded the babel package. That package provides typographic support tools for a lot of languages, such as proper hyphenation rules for the chosen language and translations for implicit terms. For example, we used the english option with babel and got Chapter 1 in our chapter heading. If we choose french instead of english, we will get Chapitre 1 in our heading.

默认为美式英语。对于英式英语,我们会使用babel的british选项。两者之间的差异非常小。例如,在英式英语中,有些单词的拼写不同,连字符规则也有些不同。

American English is the default. For British English, we would use the british option to babel. There are very small differences between the two. In British English, some words are spelled differently, and hyphenation rules are a bit different, for example.

我们加载了blindtext包,该包已开发用于生成填充文本。它使用babel来检测文档的语言;我们向babel声明了语言english,这实际上意味着美式英语。如果没有babelblindtext将默认使用拉丁填充文本。

We loaded the blindtext package, which has been developed to produce filler text. It uses babel to detect the language of the document; we stated the language english to babel, which actually means American English. Without babel, blindtext would use Latin filler text by default.

命令\blindtext打印一些虚拟文本来填充空间。

The command \blindtext prints some dummy text just to fill the space.

命令\chapter产生了一个大标题,它总是从新的一页开始。

The command \chapter produced a large heading, which will always begin on a new page.

我们已经看到了\section命令。这是我们的第二个分段级别,生成比\chapter更小​​的标题。此标题的编号由 LaTeX 自动更新。

We've already seen the \section command. It's our second sectioning level and generates a smaller heading than \chapter. The numbering of this heading is automatically updated by LaTeX.

最后,我们使用\subsection命令细化了分段,然后是更多的虚拟文本来填充页面。

Lastly, we refined the sectioning with the \subsection command followed by more dummy text to fill up the page.

Lorem ipsum 填充文本

Lorem ipsum filler text

还有另一个用于生成虚拟文本的流行包。它被称为lipsum它产生著名的Lorem Ipsum文本,多年来一直是排字机的虚拟文本。

There's another popular package for generating dummy text. It's called lipsum and it produces the famous Lorem Ipsum text, which has been the typesetter's dummy text for years.

现在让我们看看如何更改默认边距大小。

Now let's see how to change the default margin sizes.

定义边距

Defining the margins

出版商或主管可能会要求您遵循他们的文档规范。除了字体大小、行间距和其他样式问题外,可能还有边距规范。在这种情况下,您需要覆盖 LaTeX 的建议,精确指定边距。

A publisher or a supervisor may request that you follow their specifications for a document. Besides font size, interline spacing, and other style issues, there may be specifications for the margins. In this case, you would need to override LaTeX's recommendations, specifying the margins precisely.

有一个包可以满足这些需求,称为几何学。我们将加载几何包并说明所有边距的确切宽度和高度:

There's a package that fulfills these demands, called geometry. We shall load the geometry package and state the exact width and height of all margins:

  1. 使用此命令扩展本章上一个示例的序言:

    \usepackage[a4paper, inner=1.5cm, outer=3cm, top=2cm, bottom=3cm, bindingoffset=0.5cm]{geometry}

  2. Extend the preamble of the previous example in this chapter with this command:

    \usepackage[a4paper, inner=1.5cm, outer=3cm, top=2cm, bottom=3cm, bindingoffset=0.5cm]{geometry}

  3. 单击Typeset编译代码并检查调整后的边距。
  4. Click on Typeset to compile the code and examine the adjusted margins.

geometry包负责我们关于纸张大小、边距和其他尺寸的布局我们选择了 A4 纸尺寸,外边距为 3 厘米,内边距仅为 1.5 厘米。

The geometry package takes care of our layout regarding the paper size, margins, and other dimensions. We chose the A4 paper size, an outer margin of 3 cm, and an inner margin of just 1.5 cm.

内边距与外边距

Inner versus outer margins

当双面书摊开在我们面前,里面的两个边缘将被视为一个连接的空白空间。当我们的目标是相等的边距(左、中、右)时,我们可以选择内边距为外边距大小的一半。这就是外边距比内边距宽的原因。可能有理由让内边距稍微宽一点——我们以后可能会因为胶合或装订等装订而失去这样的空间。但这取决于绑定的种类,然后通过额外的bindingoffset选项完成。

When a two-sided book lies open in front of us, the two inner margins will be perceived as one joined empty space. When we aim for equal margins—left, middle, and right—we can choose for the inner margin to be half of the size of the outer margin. That's the reason why outer margins are wider than inner margins. There could be a reason to make the inner margin just a bit wider – we might lose such space later because of binding such as gluing or stapling. But this depends on the kind of binding, and then it's done with an extra bindingoffset option.

我们定义上边距为 2 厘米,下边距为 3 厘米。最后,我们为绑定校正指定了 0.5 厘米的值。

We defined the top margin to be 2 cm, and the bottom margin to be 3 cm. Lastly, we specified a value of 0.5 cm for a binding correction.

在 LaTeX 的早期,直接操作布局尺寸是很常见的。这种方法有一些缺点。我们在计算长度时很容易出错,例如左边距加上右边距加上文本宽度可能不适合纸张宽度。

In the early days of LaTeX, it was common to manipulate the layout dimensions directly. This approach had some disadvantages. We could easily make mistakes in calculating the lengths, for instance, the left margin plus the right margin plus the text width might not fit the paper width.

这是几何包的地方来救援,它提供了一个舒适的界面来指定布局参数。此外,它还提供自动完成、计算缺失值以匹配纸张尺寸,甚至使用启发式方法添加缺失长度以实现良好的布局。

This is where the geometry package comes to the rescue, which provides a comfortable interface for specifying layout parameters. Further, it provides auto-completion, calculates missing values to match the paper size, and even adds missing lengths using a heuristic approach to achieve a good layout.

geometry包理解形式为"key=value"选项,以逗号分隔。如果您加载不带参数的几何图形,则可以通过调用\geometry{argument list}来使用这些参数。

The geometry package understands options of the form "key=value", separated by commas. If you load geometry without arguments, those arguments could alternatively be used by calling \geometry{argument list}.

让我们仔细看看这些用于控制页面布局各个方面的几何包选项。

Let's take a closer look at such geometry package options to control all aspects of the page layout.

选择纸张尺寸

Choosing the paper size

几何包_提供了几个选项来设置纸张大小和方向:

The geometry package provides several options to set the paper size and orientation:

  • paper=name表示论文名称,例如paper=a4paper。该软件包支持多种纸张尺寸,例如letterpaperexecutivepaperlegalpapera0papera6paperb0paperb6paper等。
  • paper=name states the paper name, for example, paper=a4paper. The package supports a lot of paper sizes, such as letterpaper, executivepaper, legalpaper, a0paper, a6paper, b0paper, b6paper, and more.
  • paperwidthpaperheight允许您自由选择纸张尺寸,例如paperwidth=7inpaperheight=10in
  • paperwidth and paperheight allow you to choose the paper dimensions freely, such as paperwidth=7in and paperheight=10in.
  • papersize={width,height}设置纸张的宽度和高度,例如papersize={7in,10in}。这是一个双值参数的例子。
  • papersize={width,height} sets the width and height of the paper, such as papersize={7in,10in}. This is an example of a double-valued argument.
  • portrait将纸张切换为纵向模式(这是默认选项),而landscape将纸张方向更改为横向模式。
  • portrait switches the paper to portrait mode (this is the default option) while landscape changes the paper orientation to landscape mode.

如果您已经指定了纸张name 到文档类,geometry将继承它。这是一般规则:所有文档类选项将自动提供给识别它们的包。

If you already specified the paper name to the document class, geometry will inherit it. This works as a general rule: all document class options will be automatically given to the packages that recognize them.

指定文本区域

Specifying the text area

文本区域可以使用以下选项进行调整:

The text area may be adjusted with these options:

  • textwidth设置文本区域的宽度,例如textwidth=140mm
  • textwidth sets the width of the text area, such as textwidth=140mm.
  • textheight表示文本区域的高度,例如textheight=180mm
  • textheight states the height of the text area, such as textheight=180mm.
  • lines提供了另一种通过行数指定文本高度的方法,例如lines=25
  • lines provides another way to specify the text height by the number of lines, such as lines=25.
  • includehead使页面的标题包含在正文区域中(此选项默认设置为false )。
  • includehead causes the header of the page to be included in the body area (this option is set to false by default).
  • includefoot使页面的页脚包含在正文区域中(此选项默认设置为false )。
  • includefoot causes the footer of the page to be included in the body area (this option is set to false by default).

设置边距

Setting the margins

可见边距的大小可以使用以下选项指定:

The size of the visible margins can be specified with these options:

  • leftright设置左右边距的宽度,比如left=2cm。将其用于单面文档。
  • left and right set the width of the left and the right margin, such as left=2cm. Use it for one-sided documents.
  • innerouter设置内外边距的宽度,比如inner=2cm。将其用于双面文档。
  • inner and outer set the width of the inner and the outer margin, such as inner=2cm. Use it for two-sided documents.
  • topbottom设置顶部和底部边距的高度,例如top=25mm
  • top and bottom set the height of the top and the bottom margin, such as top=25mm.
  • twoside切换到双边模式。这意味着左右边距将被交换在左侧页面上,也称为背面页面。
  • twoside switches to two-sided mode. This means that the left and right margins will be swapped on left-hand pages, also called verso pages.
  • 如果您的图书是印刷后用胶水、装订或其他方式装订在一起的,则装订可能会隐藏部分内页边距。您可以为bindingoffset选项设置一个值以保留宽度以补偿绑定中隐藏的内边距部分,因此可见内边距看起来与您期望的一样宽。
  • If your book is printed and glued, stapled, or otherwise bound together, the binding may hide a part of the inner margin. You can set a value to the bindingoffset option to reserve width to compensate for the part of the inner margin that's hidden in the binding, so the visible inner margin looks as wide as you expect.

这只是一个选择常用选项——还有更多。您可以直观地选择和设置一些选项——例如,\usepackage[margin=3cm]{geometry}将在纸张的每个边缘产生 3 厘米的边距,纸张尺寸来自文档类选项。

That's just a selection of commonly used options—there are many more. You could choose and set some options intuitively—for instance, \usepackage[margin=3cm]{geometry} will result in a 3 cm margin on each edge of the paper and the paper size comes from the document class option.

自动完成的工作方式如下:

The auto-completion works like this:

  • paperwidth = left + width + right,默认情况下width=textwidth
  • paperwidth = left + width + right, where width=textwidth by default
  • paperheight = top + height + bottom,默认情况下height=textheight
  • paperheight = top + height + bottom, where height=textheight by default

如果您决定在计算布局时在文本正文中包含边注,则宽度可能会比textwidth宽。如果给出每个公式右侧的两个维度,则将计算缺失的维度。这就是为什么分别指定leftright以及topbottom可能就足够了。即使只指定了一个边距,其他尺寸也将使用默认边距比率确定:

If you decide to include marginal notes within the text body when calculating the layout, the width could get wider than textwidth. If two dimensions of the right side of each formula are given, the missing dimension will be calculated. That's why it may be enough to specify left and right, and top and bottom, respectively. Even if just one margin is specified, the other dimensions will be determined using default margin ratios:

  • 顶部:底部= 2:3
  • top:bottom = 2:3
  • := 1:1 用于单面文档
  • left:right = 1:1 for one-sided documents
  • inner : outer = 2:3 双面文档
  • inner:outer = 2:3 for two-sided documents

听起来很复杂?这就是几何如何帮助您自动获得美观的尺寸,即使缺少某些值也是如此。

Sounds complicated? That's just how geometry helps you to automatically achieve good-looking dimensions even if some values are missing.

geometry包提供了详尽的手册。不要担心文档的数量;它可以指导您完成各种功能。

The geometry package provides an extensive manual. Don't be worried by the amount of documentation; it's offered to guide you through the various features.

正如我们在第 1 章LaTeX入门中看到的,我们可以通过在命令中键入texdoc geometry打开手册线,即终端窗口,或在互联网上https://texdoc.org/pkg/geometry

As we saw in Chapter 1, Getting Started with LaTeX, we can open the manual by typing texdoc geometry at the command line, that is, a terminal window, or on the internet at https://texdoc.org/pkg/geometry.

现在我们知道如何设置基本的页面几何形状,我们将看看选项来改变文本布局,例如横向和多列。

Now that we know how to set up the basic page geometry, we'll take a look at options to change the text layout, such as to landscape orientation and having multiple columns.

使用类选项

Using class options

我们已经知道文档类是我们文档的基础。它提供命令和环境扩展 LaTeX 标准功能。虽然类提供默认样式,可以使用文档类选项自定义。

We already know that a document class is the basis of our document. It provides commands and environments extending the LaTeX standard features. Though the class provides a default style, it's customizable with document class options.

我们将第一个示例的方向更改为横向。我们还想将我们的文本排版成两列:

We shall change the orientation of our first example to landscape. We would also like to typeset our text in two columns:

  1. 将选项landscapetwocolumn添加到我们示例的\documentclass语句中,如下所示:

    \documentclass[a4paper,12pt,landscape,twocolumn]{book}

  2. Add the options landscape and twocolumn to the \documentclass statement of our example, as follows:

    \documentclass[a4paper,12pt,landscape,twocolumn]{book}

  3. 加载几何包:

    \usepackage{几何}

  4. Load the geometry package:

    \usepackage{geometry}

  5. 点击Typeset进行编译,看看布局发生了怎样的变化:
  6. Click on Typeset to compile, and see how the layout has changed:
图 3.2 – 横向两栏页面布局

图 3.2 – 横向两栏页面布局

Figure 3.2 – A landscape two-column page layout

通过使用横向选项,我们将页面方向从纵向切换为横向。通过使用twocolumn选项,我们将正文分为两列。

By using the landscape option, we switched the page orientation from portrait to landscape. By using the twocolumn option, we caused the body text to be divided into two columns.

我们加载了几何在横向模式下获得正确的 PDF 页面大小。没有它,PDF 将保持纵向模式。

We loaded the geometry package to get the proper PDF page size in landscape mode. Without it, the PDF would remain in portrait mode.

命令\twocolumn[opening text]开始一个两栏的页面,在整个宽度上有可选的开始文本。\onecolumn开始单栏页面。如果您想平衡最后一页上的列,或者如果您希望有两列以上,请使用multicols包。

The command \twocolumn[opening text] starts a two-column page with optional opening text over the whole width. \onecolumn begins a one-column page. If you'd like to balance the columns on the last page or if you wish to have more than two columns, use the multicols package.

LaTeX 基类是articlebookreportslidesletter。顾名思义,最后一个可以用来写字母,尽管还有更合适的类,例如scrlttr2

The LaTeX base classes are article, book, report, slides, and letter. As the name suggests, the last one can be used to write letters, though there are further suitable classes, such as scrlttr2.

幻灯片可用于创建演示文稿,但现在有更强大、功能更丰富的类,例如beamerpowerdot

slides can be used to create presentations, but today there are more powerful and feature rich classes, such as beamer and powerdot.

让我们总结一下基类的选项:

Let's sum up the options of the base classes:

  • a4papera5paperb5paperletterpaperlegalpaperexecutivepaper:输出将根据此纸张大小进行格式化;例如,A4 将被格式化为 210mm x 297mm。信纸选项(8.5 英寸 x 11 英寸是默认选项。加载几何包允许更多尺寸。
  • a4paper, a5paper, b5paper, letterpaper, legalpaper, or executivepaper: The output will be formatted according to this paper size; for example, A4 will be formatted as 210mm x 297mm. The letterpaper option (8.5 in x 11 in) is the default. Loading the geometry package allows more sizes.
  • 10pt11pt12pt:文档中普通文本的大小;默认值为 10 点 ( 10pt )。标题、脚注、索引等的大小将相应调整。
  • 10pt, 11pt, or 12pt: The size of normal text in the document; the default is 10 points (10pt). The size of headings, footnotes, indexes, and so on, will be adjusted accordingly.
  • landscape:切换到横向格式;输出尺寸的宽度和高度将互换。
  • landscape: Switches to landscape format; the width and height of the output size will be interchanged.
  • onecolumntwocolumn:决定页面是单栏(默认)还是双栏。letter类不支持它。
  • onecolumn or twocolumn: Decides whether the pages will be one-column (default) or two-column. It's not supported by the letter class.
  • onesidetwoside:格式化用于在页面的一面或两面打印。oneside是默认值,书籍类除外。twoside不能用于幻灯片类和字母类。
  • oneside or twoside: Formatting for printing on one side or both sides of a page. oneside is the default, except for the book class. twoside is not usable with the slides class and the letter class.
  • openrightopenany:第一个选项决定章节必须从右侧页面开始(书籍的默认设置),而第二个选项允许章节从任何页面开始(报告类的默认设置)。这些选项仅受书籍报告类支持,因为其他类不提供章节。
  • openright or openany: The first option decides that chapters have to begin on a right-hand page (the default for the book class), while the second option allows chapters to start on any page (the default for the report class). These options are only supported by the book and the report class because the other classes don't provide chapters.
  • titlepagenotitlepage:第一个在使用\maketitle时会导致单独的标题页,并且是默认设置,除了文章类。article的默认值是notitlepage,这意味着普通文本可以跟在同一页的标题后面。
  • titlepage or notitlepage: The first causes a separate title page when \maketitle is used and is the default, except for the article class. The default of article is notitlepage, which means that normal text may follow the title on the same page.
  • finaldraft:如果设置了draft,那么 LaTeX 将用黑框标记过满的行,这有助于查看和改进输出。一些包也支持这些选项,然后表现不同,例如在选择草稿时省略图形和列表的嵌入。final是默认值。
  • final or draft: If draft is set, then LaTeX will mark overfull lines with a black box, which is helpful in reviewing and improving the output. Some packages support these options as well, behaving differently then, such as omitting the embedding of graphics and listings when a draft has been chosen. final is the default.
  • openbib:设置此选项后,参考书目将以开放式而不是压缩式格式化。
  • openbib: When this option is set, a bibliography will be formatted in open style instead of compressed style.
  • fleqn:使显示的公式左对齐。
  • fleqn: Causes displayed formulas to be left-aligned.
  • leqno:对于编号显示的公式,数字将放在左侧。右侧是默认值。
  • leqno: For numbered displayed formulas, the number will be put on the left side. The right side is the default.

许多其他类也支持这些选项,甚至更多。对于不常见的基本字体大小,类extarticleextbookextreportextletter提供从 8 磅到 20 磅的基本字体大小。KOMA -Script允许任意基本字体大小。他们了解如此多的选项,以至于他们还支持key=value接口,正如我们在geometry包中看到的那样。

Many other classes support these options as well, and even more. For an uncommon base font size, the classes extarticle, extbook, extreport, and extletter provide base font sizes from 8 points to 20 points. The KOMA-Script classes allow arbitrary base font sizes. They understand such a large amount of options that they additionally support a key=value interface as we saw with the geometry package.

KOMA脚本

KOMA-Script

KOMA脚本类可以像基类一样使用:对于每个基类,都有一个对应的 KOMA 类。它们非常扩展基类,提供了大量的命令和选项用于定制。访问https://texdoc.org/pkg/koma-script打开手册。

KOMA-Script classes may be used like base classes: for each base class, there's a corresponding KOMA class. They extend base classes very much, providing a large set of commands and options for customizing. Visit https://texdoc.org/pkg/koma-script to open the manual.

由于已经提到页眉,现在让我们探讨一下。

As page headers have been mentioned, let's explore them now.

设计页眉和页脚

Designing headers and footers

当我们测试我们的第一个版本时例如,您可能已经注意到,除了章节开始的页面外,所有页面的页眉中都显示了页码、章节标题和章节标题。因此,在我们的双面布局中,第2页是左侧页眉,页码位于外边距,此处位于左侧:

When we tested the first version of our example, you might have noticed that except for the page where the chapter started, all pages showed the page number, chapter title, and section title in their header. So, in our two-sided layout, on page 2, which is a left-hand page header, the page number is in the outer margin, here on the left side:

图 3.3 – 第 2 页的标题

图 3.3 – 第 2 页的标题

Figure 3.3 – The header of page 2

这就是第3页右侧页眉的样子,页码位于外边距,现在位于右侧:

And this is how our right-hand page header on page 3 looks, with the page number in the outer margin, which is on the right side now:

图 3.4 – 第 3 页的标题

图 3.4 – 第 3 页的标题

Figure 3.4 – The header of page 3

在单侧布局中,页眉布局不会有这样的差异。单侧布局中的标题如图3.4所示。默认情况下,标题文本在左侧,页码在右侧。

In a one-sided layout, there would not be such a difference in the header layout. The headers in a one-sided layout are as in Figure 3.4. By default, heading text is on the left side, and the page number is on the right side.

尽管这些标准标头已经非常有用,但我们将了解如何自定义它们以满足我们的个性化需求。

Though these standard headers are already quite useful, we shall see how to customize them to meet our individual requirements.

默认形状页面标题是倾斜的。此外,它们是用大写字母书写的。我们将使用粗体字代替,我们将使用小型大写字体作为章节标题。我们将加载fancyhdr包并使用它的命令来实现:

The default shape of the page headings is slanted. Furthermore, they are written in capital letters. We shall use bold typeface instead and we will use a small-caps font for the chapter title. We will load the fancyhdr package and use its commands to achieve that:

  1. 载入本章的第一个例子。
  2. Load the first example of this chapter.
  3. 插入突出显示的行以获取此内容:

    \documentclass[a4paper,12pt]{book}

    \usepackage[english]{babel}

    \usepackage{盲文}

    \usepackage{fancyhdr}

    \花式{}

    \fancyhead[LE]{\scshape\nouppercase{\l​​eftmark}}

    \fancyhead[RO]{\nouppercase{\rightmark}}

    \fancyfoot[LE,RO]{\thepage}

    \pagestyle{花式}

    \开始{文档}

    \chapter{探索页面布局}

    在本章中,我们将学习页面的布局。

    \section{一些填充文字}

    \盲文

    \section{更多填充文本}

    更多虚拟文本将随之而来。

    \subsection{大量填充文字}

    \盲文[10]

    \end{文档}

  4. Insert the highlighted lines to get this:

    \documentclass[a4paper,12pt]{book}

    \usepackage[english]{babel}

    \usepackage{blindtext}

    \usepackage{fancyhdr}

    \fancyhf{}

    \fancyhead[LE]{\scshape\nouppercase{\leftmark}}

    \fancyhead[RO]{\nouppercase{\rightmark}}

    \fancyfoot[LE,RO]{\thepage}

    \pagestyle{fancy}

    \begin{document}

    \chapter{Exploring the page layout}

    In this chapter we will study the layout of pages.

    \section{Some filler text}

    \blindtext

    \section{A lot more filler text}

    More dummy text will follow.

    \subsection{Plenty of filler text}

    \blindtext[10]

    \end{document}

  5. 编译代码。页脚将在其外侧包含页码。

    右侧页面标头现在如下所示:

  6. Compile the code. The footers will contain the page number on their outer side.

    A right-hand page header now looks like the following:

图 3.5 – 第 2 页的新标题

图 3.5 – 第 2 页的新标题

Figure 3.5 – The new header of page 2

左侧标题现在如下所示:

A left-hand header now looks like this:

图 3.6 – 第 3 页的新标题

图 3.6 – 第 3 页的新标题

Figure 3.6 – The new header of page 3

我们加载了fancyhdr包,它提供了自定义页眉和页脚的命令。包命令名称以\fancy开头。我们的第一个动作是调用\fancyhf{};此命令清除页眉和页脚。此外,我们使用了以下内容:

We loaded the fancyhdr package, which provides commands for customizing headers and footers. The package command names start with \fancy. Our first action was calling \fancyhf{}; this command clears the headers and footers. Furthermore, we used the following:

  • \leftmark :书籍类使用它来存储章节标题和章节编号。默认使用大写字母。
  • \leftmark: Used by the book class to store the chapter title together with the chapter number. Capital letters are used as default.
  • \rightmark :书籍类使用它来存储章节标题及其编号。也使用大写字母。
  • \rightmark: Used by the book class to store the section title together with its number. Capital letters are used as well.
  • \nouppercase:这会在其参数中禁用(默认)大写。
  • \nouppercase: This disables the (default) uppercase in its argument.
  • \scshape:我们切换到小型大写字体。
  • \scshape: We switched to a small-caps font.

我们使用带有可选参数LE 的命令\fancyhead来放置章节标题到页眉。LE代表 left-even,表示本章标题将放在偶数页页眉的左侧。

We used the command \fancyhead with the optional argument LE to put the chapter title into the header. LE stands for left-even and means that this chapter title will be put on the left side of the header on even-numbered pages.

相反,我们用RO调用命令\fancyhead将节标题放入标题中。RO代表right-odd,意思是这个section heading应该显示在奇数页页眉的右边。

Conversely, we called the command \fancyhead with RO to put the section title into the header. RO stands for right-odd and means that this section heading shall be displayed on the right side of the header on odd-numbered pages.

之后,我们使用\fancyfoot在页脚中显示页码。这一次,我们使用了LERO,它在偶数页和奇数页上显示页码,总是在外侧。然后命令\thepage打印页码。

Afterward, we used \fancyfoot to display the page number in the footer. This time, we used LE and RO, which showed the page number on both even and odd pages, always on the outer side. Then the command \thepage prints the page number.

所有这些命令都用于修改fancyhdr提供的页面样式;这种风格被称为花式。我们不得不告诉 LaTeX 使用这种风格,我们通过\pagestyle{fancy}做到了。

All those commands are used to modify a page style provided by fancyhdr; this style is called fancy. We had to tell LaTeX to use this style and we did it through \pagestyle{fancy}.

通过编写所有字母大写来强调,就像fancyhdr默认情况下所做的那样,称为全部大写。它被广泛视为作为一种可疑的风格。这就是我们转向小型股的原因。

Emphasizing by writing all letters capitalized, as fancyhdr does by default, is called all caps. It is widely regarded as a questionable style. That's why we moved to small caps.

标题有不同的样式和页脚。这种组合称为页面样式。让我们看看有哪些页面样式可用。

There are different styles of headers and footers. That combination is called a page style. Let's see what page styles are available.

了解页面样式

Understanding page styles

LaTeX 及其基类提供四种页面样式:

LaTeX and its base classes provide four page styles:

  • empty:既不显示页眉也不显示页脚。
  • empty: Neither a header nor a footer is shown.
  • 普通:没有标题。页码将被打印并在页脚居中。
  • plain: No header. The page number will be printed and centered in the footer.
  • headings:页眉包含章、节和/或小节的标题,具体取决于类别和页码。页脚是空的。
  • headings: The header contains titles of chapters, sections, and/or subsections, depending on the class and also the page number. The footer is empty.
  • myheadings:页眉包含用户定义的文本和页码;页脚是空的。
  • myheadings: The header contains user-defined text and the page number; the footer is empty.

fancyhdr添加了一种名为fancy的页面样式,它允许用户自定义页眉和页脚。

fancyhdr adds one page style called fancy, which allows the user to customize both the header and the footer.

可以使用两个命令来选择页面样式:

Two commands may be used to choose the page style:

  • \pagestyle{name}:从此时开始切换到页面样式名称。
  • \pagestyle{name}: Switches to the page style name from this point onwards.
  • \thispagestyle{name} : 仅选择页面样式名称或当前页面;以下页面将具有以前使用过的样式。
  • \thispagestyle{name}: Chooses the page style name only or the current page; the following pages will have the style that's been used before.

你已经看到了一章开始,页面风格不同于其他页面的风格。这样的页面将具有朴素的风格。如果您认为所有页面都应该使用相同的样式,请查看一些书籍:章节开头的样式不同是很常见的。他们通常有一个空白标题。\thispagestyle可以用来覆盖它。

You have seen that where a chapter starts, the page style is different from the style of other pages. Such pages will have a plain style. If you thought all pages should use the same style, look into some books: it's very common that chapter beginnings differ in style. They usually have a blank header. \thispagestyle could be used to override that.

可以修改页眉和页脚中的内容和位置,我们将在接下来看到。

Content and positioning in headers and footers can be modified, as we will see next.

自定义页眉和页脚

Customizing headers and footers

让我们划分标题和页脚分为六部分:左、中和右(lcr),用于页眉和页脚。修改这些区域的命令如下:

Let's divide the header and footer into six pieces: left, center, and right (l, c, r) both for the header and footer. The commands to modify those areas are as follows:

  • 对于标头:\lhead\chead\rhead
  • For the header: \lhead, \chead, \rhead
  • 对于页脚:\lfoot\cfoot\rfoot
  • For the footer: \lfoot, \cfoot, \rfoot

这些命令中的每一个都需要一个强制参数,例如\chead{User's guide}\cfoot{\thepage}。该参数将被放入页面的相应区域。

Each of these commands requires a mandatory argument, such as \chead{User's guide} or \cfoot{\thepage}. This argument will be put into the corresponding area of the page.

或者,您可以使用这些通用命令:

Alternatively, you could use these versatile commands:

  • 对于标题:\fancyhead[code]{text}
  • For the header: \fancyhead[code]{text}
  • 对于页脚:\fancyfoot[code]{text}
  • For the footer: \fancyfoot[code]{text}

在这里,代码可能包括一个或多个字母的:

Here, code may consist of one or more letters:

  • 大号:左
  • L: left
  • C:中心
  • C: center
  • R : 对
  • R: right
  • E:偶数页
  • E: even page
  • O : 奇数页
  • O: odd page

我们选择大写字母还是小写字母都没有关系。我们已经在示例中使用了此类组合。

It doesn't matter if we choose uppercase or lowercase letters. We already used such combinations in our example.

其他自定义是修改文本和页脚之间的分隔线。

Another customization is modifying the separation line between the text and the footer.

在页眉或页脚中使用装饰线

Using decorative lines in headers or footers

我们可以引入或删除标题之间的行以及正文、正文和页脚,分别使用以下两个命令:

We can introduce or delete lines between the header and the body text and the body text and the footer, respectively, with these two commands:

  • \renewcommand{\headrulewidth}{width}
  • \renewcommand{\headrulewidth}{width}
  • \renewcommand{\footrulewidth}{width}
  • \renewcommand{\footrulewidth}{width}

此处,宽度可以是1pt0.5mm等值。标题行的默认值为0.4pt ,页脚行的默认值为0pt 。0pt表示一条线不可见。

Here, width may be a value such as 1pt, 0.5mm, and so on. The default is 0.4pt for the header line and 0pt for the footer line. 0pt means that a line is not visible.

\newcommand定义新命令,而\renewcommand重新定义现有命令。顺便说一句,我们必须了解一个新概念:许多 LaTeX 命令可能会以这种方式重新定义。这可以像这里一样简单地更改值或重新定义命令的代码。

While \newcommand defines a new command, \renewcommand redefines an existing command. Incidentally, we've got to know a new concept: a lot of LaTeX commands may be redefined in this way. This can be simply changing a value like here or redefining the code for a command.

更改 LaTeX 的标题标记

Changing LaTeX's header marks

我们已经知道,LaTeX 类和包自动在宏\leftmark\rightmark中存储切片编号和标题。这将在我们调用\chapter\section\subsection时完成。所以,我们可以在fancyhdr命令的参数中使用\leftmark\rightmark

As we already know, LaTeX classes and packages store sectioning numbers and headings in the macros \leftmark and \rightmark automatically. It will be done when we call \chapter, \section, or \subsection. So, we could just use \leftmark and \rightmark in the arguments of the fancyhdr commands.

有时我们会希望手动更改这些条目,即使我们依赖于这种自动化。例如,带星号的分节命令,如\chapter*\section*不会产生标题条目,如前所述。在这种情况下,两个命令将帮助我们:

We will sometimes want to change those entries manually, even if we rely on this automation. For instance, the starred sectioning commands such as \chapter* and \section* won't produce a header entry, as indicated earlier. In such a case, two commands will help us:

  • \markright{right head}设置右标题。
  • \markright{right head} sets the right heading.
  • \markboth{left head}{right head}设置左右标题。
  • \markboth{left head}{right head} sets both the left and right headings.

默认样式标题易于使用并提供良好的效果。myheadings可以与\markright\markboth一起使用。然而,最灵活的方式是由fancyhdr给出的,特别是结合\markright\markboth

The default style headings is easy to use and gives good results. myheadings can be used together with \markright and \markboth. However, the most flexible way is given by fancyhdr, especially in combination with \markright and \markboth.

fancyhdr的一个很好的替代品是名为scrpage-scrlayer 的包。它属于 KOMA-Script,但scrpage-scrlayer也适用于其他类。它提供类似的功能,并提供更多的功能。

A very good alternative to fancyhdr is the package called scrpage-scrlayer. It belongs to KOMA-Script, but scrpage-scrlayer works with other classes as well. It provides similar functionality and offers even more features.

页脚是添加注释的好地方。让我们在下一节中看看如何做到这一点。

The footer is a good place to add notes. Let's see how to do that in the next section.

使用脚注

Using footnotes

如前所述第 2 章格式化文本和创建宏中,LaTeX 提供了一个命令来排版脚注。让我们看看它的实际效果。

As briefly mentioned in Chapter 2, Formatting Text and Creating Macros, LaTeX provides a command to typeset footnotes. Let's see it in action.

让我们回到本章的第一个例子。我们将在正文中插入一个脚注,在节标题中插入一个脚注:

Let's go back to the very first example of this chapter. We shall insert one footnote in the body text and one in a section heading:

  1. 修改插入脚注的示例,如突出显示的行所示:

    \documentclass[a4paper,12pt]{book}

    \usepackage[english]{babel}

    \usepackage{盲文}

    \开始{文档}

    \chapter{探索页面布局}

    在本章中,我们将学习页面的布局。

    \section{一些填充文字}

    \盲文

    \section{更多填充文本}

    更多虚拟文本\脚注{作为占位符}

    将遵循。

    \subsection{大量填充文字}

    \盲文[10]

    \end{文档}

  2. Modify the example inserting a footnote, as shown in the highlighted line:

    \documentclass[a4paper,12pt]{book}

    \usepackage[english]{babel}

    \usepackage{blindtext}

    \begin{document}

    \chapter{Exploring the page layout}

    In this chapter we will study the layout of pages.

    \section{Some filler text}

    \blindtext

    \section{A lot more filler text}

    More dummy text\footnote{serving as a placeholder}

    will follow.

    \subsection{Plenty of filler text}

    \blindtext[10]

    \end{document}

  3. 编译代码查看脚注在打印中的外观:
  4. Compile the code to see how the footnote looks in print:
图 3.7 – 带脚注的文本

图 3.7 – 带脚注的文本

Figure 3.7 – Text with a footnote

命令\footnote{text}在当前位置放置一个带上标的数字。

The command \footnote{text} placed a superscripted number at the current position.

此外,它在页面底部打印其参数文本,并用相同的数字标记。正如我们所见,这些注释与正文之间用一条水平线隔开。

Furthermore, it prints its argument text at the bottom of the page, marked by the same number. As we've seen, such notes are separated from the main text by a horizontal line.

\footnote[number]{text}产生由这个可选数字标记的脚注,一个整数。如果我们不提供可选编号,将使用内部计数器。这将自动完成;我们不用担心。

\footnote[number]{text} produces a footnote marked by this optional number, an integer. If we don't give the optional number, an internal counter will be stepped and used. This will be done automatically; we don't need to worry.

还有两个额外的命令可以帮助我们有选择地只放置脚注标记或文本:

There are two additional commands that help us selectively put only a footnote mark or text:

  • \footnotemark[number]在文本中产生一个带上标的数字作为脚注标记。如果没有给出可选参数,它也会步进并使用内部脚注计数器。不会生成脚注文本。
  • \footnotemark[number] produces a superscripted number in the text as a footnote mark. If the optional argument wasn't given, it's also stepping and using the internal footnote counter. No footnote text will be generated.
  • \footnotetext[number]{text}生成脚注文本而不在文本中放置脚注标记,并且它不会增加内部脚注计数器。
  • \footnotetext[number]{text} generates footnote text without putting a footnote mark in the text, and it does not step up the internal footnote counter.

在相关文本后立即设置脚注命令。不要在中间留一个空格,否则,文本和下面的脚注标记之间会出现空隙。

Set a footnote command right after the related text. Don't leave a space in-between, otherwise, you would get a gap between the text and the following footnote mark.

图 3.7中,我们看到将脚注与文本分开的一行。我们现在将看到如何调整这条线。

In Figure 3.7, we saw a line that separates the footnotes from the text. We will now see how to adjust that line.

修改脚注行

Modifying the footnote line

分隔脚注的线从文本是由命令\footnoterule产生的。如果我们想省略那行或者如果我们想修改它,我们必须重新定义它。我们之前了解过\renewcommand,所以让我们使用它。

The line that separates footnotes from the text is produced by the command \footnoterule. If we wish to omit that line or if we want to modify it, we must redefine it. We learned about \renewcommand earlier, so let's use it.

我们将使用\renewcommand覆盖默认的\footnoterule命令:

We will use \renewcommand to override the default \footnoterule command:

  1. 以前面的示例为例,将以下几行添加到序言中:

    \renewcommand{\footnoterule}

    {\noindent\smash{\rule[3pt]{\textwidth}{0.4pt}}}

  2. Take the previous example and add the following lines to the preamble:

    \renewcommand{\footnoterule}

    {\noindent\smash{\rule[3pt]{\textwidth}{0.4pt}}}

  3. 点击Typeset进行编译,看看这一行发生了怎样的变化:
  4. Click on Typeset to compile, and see how the line has changed:
图 3.8 – 修改后的脚注行

图 3.8 – 修改后的脚注行

Figure 3.8 – A modified footnote line

现有的\footnoterule命令将替换为我们在第一步的第二行中编写的新定义。命令\rule[raising]{width}{height}绘制一条线,这里 0.4 pt 粗,和文本一样宽,凸起一点,3 pt。通过\smash命令,我们让我们的线条假装高度和深度为零,因此它根本不占用任何垂直空间。这样,页面平衡就不会受到影响。您已经知道\noindent,它避免了段落缩进。

The existing \footnoterule command will be replaced by the new definition that we wrote in the second line of the first step. The command \rule[raising]{width}{height} draws a line, here 0.4 pt thick, and as wide as the text, raised a bit, by 3 pt. Through the \smash command, we let our line pretend to have a height and a depth of zero, so it's occupying no vertical space at all. This way, the page balancing will not be affected. You already know \noindent, which avoids the paragraph indentation.

如果您想完全省略该脚注行,只需编写以下内容:

If you want to omit that footnote line completely, you just need to write the following:

\renewcommand{\footnoterule}{}

\renewcommand{\footnoterule}{}

现在命令被定义为什么都不做,我们不会得到分界线。

Now the command is defined to do nothing, and we won't get a dividing line.

使用包扩展脚注样式

Using packages to expand footnote styles

有不同的习惯用于设置脚注。一些样式需要每页编号的脚注,它们可能必须作为所谓的尾注放在文档中,并且可以使用符号而不是数字。存在更多的需求,因此已经开发了几个包来满足它们。这是一个选择:

There are different habits for setting footnotes. Some styles require footnotes numbered per page, they might have to be placed in the document as so-called endnotes, and symbols instead of numbers may be used. More demands exist and therefore several packages have been developed to comply with them. Here's a selection:

  • endnotes:在文档末尾放置脚注
  • endnotes: Places footnotes at the end of the document
  • manyfoot : 允许嵌套脚注
  • manyfoot: Allows nested footnotes
  • bigfoot:替换和扩展manyfoot并使用脚注改进分页处理
  • bigfoot: Replaces and extends manyfoot and improves page break handling with footnotes
  • savefnmark:当你需要多次使用脚注时很有用
  • savefnmark: Useful when you need to use footnotes several times
  • footmisc:一个全方位的包;每页引入编号,当使用许多短脚注时能够节省空间,提供符号而不是数字作为脚注标记,提供悬挂缩进和其他样式
  • footmisc: An all-round package; introduces numbering per page, is able to save space when many short footnotes are used, offers symbols instead of numbers as footnote marks, provides hanging indentation and other styles

看看相应的包装文件使用texdoc命令了解更多信息,如第 1 章LaTeX 入门中所述,或https://texdoc.org

Have a look at the respective package documentation to learn more using either the texdoc command, as explained in Chapter 1, Getting Started with LaTeX, or at https://texdoc.org.

正如我们讨论过页面末尾的脚注一样,让我们​​看看如何强制自己结束页面,以防我们不想让它自动发生。

As we've talked about footnotes at the end of a page, let's see how to enforce ending a page ourselves in case we don't want to let it automatically happen.

断页

Breaking pages

正如您在我们的示例中所见,LaTeX本身负责分页。有时我们想在 LaTeX 之前自己插入一个分页符。LaTeX 提供了几个命令来做到这一点,有或没有垂直平衡。

As you've seen in our example, LaTeX itself took care of the page breaking. There might be occasions where we'd like to insert a page break ourselves before LaTeX does. LaTeX offers several commands to do so, with vertical balance or without.

我们现在回到示例的第一个版本,我们将在 1.2.1 小节之前手动插入一个分页符:

We will now go back to the first version of our example and we shall manually insert a page break right before subsection 1.2.1:

  1. 将突出显示的行插入到我们的示例中,其中包含\pagebreak命令:

    \documentclass[a4paper,12pt]{book}

    \usepackage[english]{babel}

    \usepackage{盲文}

    \开始{文档}

    \chapter{探索页面布局}

    在本章中,我们将学习页面的布局。

    \section{一些填充文字}

    \盲文

    \section{更多填充文本}

    更多虚拟文本将随之而来。

    \分页符

    \subsection{大量填充文字}

    \盲文[10]

    \end{文档}

  2. Insert the highlighted line into our example, which contains the \pagebreak command:

    \documentclass[a4paper,12pt]{book}

    \usepackage[english]{babel}

    \usepackage{blindtext}

    \begin{document}

    \chapter{Exploring the page layout}

    In this chapter we will study the layout of pages.

    \section{Some filler text}

    \blindtext

    \section{A lot more filler text}

    More dummy text will follow.

    \pagebreak

    \subsection{Plenty of filler text}

    \blindtext[10]

    \end{document}

  3. 编译代码并查看结果:
    图 3.9 – 拉伸的页面

    图 3.9 – 拉伸的页面

  4. Compile the code and take a look at the result:

    Figure 3.9 – A stretched page

  5. 代替 \pagebreak\newpage
  6. Replace \pagebreak with \newpage.
  7. 再次编译,比较:
  8. Compile again, and compare:
图 3.10 – 一个未拉伸的页面

图 3.10 – 一个未拉伸的页面

Figure 3.10 – A non-stretched page

一开始,我们插入命令\pagebreak;顾名思义,它会导致分页。此外,文本已被拉伸以填满页面直至底部。这对于在所有页面上具有相同的文本高度可能是可取的。

At first, we inserted the command \pagebreak; as its name suggests, it causes a page break. Furthermore, the text has been stretched to fill the page down to the bottom. That can be desirable for having the same text height on all pages.

之后,由于段落和标题之间明显令人不快的空白,我们将\pagebreak替换为\newpage。此命令也会打断页面,但不会拉伸文本:页面的剩余空间将保持空白。

Afterward, because of the obviously unpleasant whitespace between the paragraphs and the headings, we replaced \pagebreak with \newpage. This command breaks the page as well, but it doesn't stretch the text: the remaining space of the page will stay empty.

因此,\pagebreak 的行为类似于\linebreak,而\newpage 的行为类似于\newline(用于页面而不是行)。甚至还有一个\nopagebreak命令类似于\nolinebreak并禁止分页。\pagebreak不会换行,而\nopagebreak不指行的中间;这两个命令都适用于当前行的末尾。当然,它们在段落之间使用时会立即产生效果。

So, \pagebreak behaves like \linebreak, and \newpage works like \newline (for pages instead of lines). There's even a \nopagebreak command that's analogous to \nolinebreak and forbids page breaking. \pagebreak won't break a line, while \nopagebreak doesn't refer to the middle of a line; both commands apply at the end of the current line. Of course, they immediately have an effect when used between paragraphs.

如果您使用双列格式,\pagebreak\newpage都将从新列而不是新页开始。

If you use the two-column format, both \pagebreak and \newpage will begin on a new column instead of a new page.

那里有两个更多变体:\clearpage与\newpage类似,除了它将在新页面上开始,即使在双列模式下也是如此。\cleardouplepage的作用相同,但会导致以下文本从右侧页面开始,必要时插入空白页。后者对双面文档很有用。

There are two further variants: \clearpage works like \newpage, except that it will start on a new page, even in two-column mode. \cleardoublepage does the same but causes the following text to start on a right-hand page, inserting a blank page if necessary. The latter is useful for two-sided documents.

更重要的是,这两个命令都会立即打印出 LaTeX 内存中的所有图形和表格。

More importantly, both commands cause all figures and tables that LaTeX has in its memory to be printed out immediately.

\pagebreak\nopagebreak可以采用一个可选参数来请求特定的换行符,如下所示。参数是一个介于 0 和 4 之间的整数。这里,0 表示允许分页符,1 表示需要分页符,2 和 3 表示更坚持的请求,因此 LaTeX 会更努力地拉伸文本以到达页面底部,而 4 将强制分页。\pagebreak\nopagebreak与我们在第 2 章格式化文本和创建宏中看到的命令对\linebreak\nolinebreak非常相似。

\pagebreak and \nopagebreak can take an optional argument that requests a certain line break, as follows. The argument is an integer between 0 and 4. Here, 0 means that a page break is allowed, 1 means it's desired, 2 and 3 mark more insistent requests so LaTeX tries harder to stretch the text to reach the page bottom, and 4 will enforce a page break. \pagebreak and \nopagebreak are very similar to the command pair \linebreak and \nolinebreak, which we saw in Chapter 2, Formatting Text and Creating Macros.

这种手动分页符减少了适合页面的文本量。现在让我们看看相反的情况:在页面上获取更多文本。

Such manual page breaks reduce the amount of text that fits on the page. Let's now look at the opposite: getting more text on a page.

放大页面

Enlarging a page

可能会有场合我们想在页面上放置更多的文本,即使文本会被挤压一点或文本高度增加。有一个命令可以帮助我们解决问题:\enlargethispage

There may be occasions where we want to put a little more text onto a page, even if the text will be squeezed a bit or the text height increases. There's a command that will help us out: \enlargethispage.

我们将稍微修改我们的示例。这一次,我们将通过挤压前​​一页上的文本来尝试避免几乎空白的页面:

We shall modify our example a bit. This time, we will try to avoid a nearly empty page by squeezing the text on the preceding page:

  1. 从我们的示例中删除\newpage命令并切换到11pt 基本字体。这一次,在小节中使用较少的填充文本:

    \documentclass[a4paper,11pt]{book}

    \usepackage[english]{babel}

    \usepackage{盲文}

    \usepackage[a4paper, inner=1.5cm, outer=3cm, top=2cm,

    bottom=3cm, bindingoffset=1cm]{geometry}

    \开始{文档}

    \chapter{探索页面布局}

    在本章中,我们将学习页面的布局。

    \section{一些填充文字}

    \盲文

    \section{更多填充文本}

    更多虚拟文本将随之而来。

    \subsection{大量填充文字}

    \盲文[3]

    \end{文档}

  2. Remove the \newpage command from our example and switch to 11pt base font. This time, use less filler text in the subsection:

    \documentclass[a4paper,11pt]{book}

    \usepackage[english]{babel}

    \usepackage{blindtext}

    \usepackage[a4paper, inner=1.5cm, outer=3cm, top=2cm,

    bottom=3cm, bindingoffset=1cm]{geometry}

    \begin{document}

    \chapter{Exploring the page layout}

    In this chapter we will study the layout of pages.

    \section{Some filler text}

    \blindtext

    \section{A lot more filler text}

    More dummy text will follow.

    \subsection{Plenty of filler text}

    \blindtext[3]

    \end{document}

  3. 编译,和结果将包含两页。这是第一页:
    图 3.11 – 一个完全填充的页面

    图 3.11 – 一个完全填充的页面

    这是第二页的文字:

    图 3.12 – 第二页上的剩余文本

    图 3.12 – 第二页上的剩余文本

  4. Compile, and the result will consist of two pages. This is the first page:

    Figure 3.11 – A fully filled page

    And this is the text on the second page:

    Figure 3.12 – Remaining text on the second page

  5. 在\subsection行之后插入此命令:

    \enlargethispage{\baselineskip}

  6. Insert this command right after the \subsection line:

    \enlargethispage{\baselineskip}

  7. 再次编译,现在我们的文档只适合一页:
  8. Compile again and now our document fits on just one page:
图 3.13 – 所有文本都适合一个页面

图 3.13 – 所有文本都适合一个页面

Figure 3.13 – All text fits on a single page

我们使用命令\enlargethispage来压缩在页面上添加更多文本。此命令将额外请求的高度作为其参数。命令\baselineskip返回我们用作参数的文本行的高度。因此,LaTeX 可以在页面上多放一行,甚至剩余的行也适合,因为 LaTeX 压缩了一些空白。

We used the command \enlargethispage to squeeze more text onto a page. This command takes the additionally requested height as its argument. The command \baselineskip returns the height of a text line that we used as the argument. So, LaTeX could put one extra line onto the page, and even the remaining line fitted in as well because LaTeX compressed some whitespace.

我们可以使用 factors: write \enlargethispage{2\baselineskip}在一个页面上得到两行。它甚至不需要是整数值。与往常一样,当您声明长度时,您可以使用其他单位,例如10pt0.5in1cm5mm,甚至是负值。

We could use factors: write \enlargethispage{2\baselineskip} to get two more lines on a page. It doesn't even need to be an integer value. As always, when you state a length, you could use other units such as 10pt, 0.5in, 1cm, or 5mm, and even negative values.

此命令仅影响当前页面。有一个加星标的版本:\enlargethispage*还会将页面上的所有垂直空间缩小到最小。

Only the current page will be affected by this command. There's a starred version: \enlargethispage* would additionally shrink all vertical spaces on the page to their minimum.

不过,应该考虑\enlargethispage当您很快需要在单个页面上放置更多文本时,只是为了可能的简单修复。一般来说,我们可以通过改变页边距来调整页面上的文字数量,我们已经知道,或者通过调整文本内的行间距。那么,让我们看看下一节中的行间距。

Though, \enlargethispage should be considered just for a possible easy fix when you quickly need to put more text on a single page. In general, we can adjust the text quantity on the page by changing the margins, as we already know, or by adjusting the line spacing within text. So, let's look at line spacing in the next section.

更改行距

Changing the line spacing

没有一些垂直行与行之间的空间,我们文本的可读性可能会受到影响。添加这样的空间将有助于沿着这条线引导视线。尽管 LaTeX 已经通过选择有意义的行间距来确保良好的可读性,但出版商可能需要不同的间距。

Without some vertical space between the lines, the readability of our text could suffer. Adding such space would help lead the eye along the line. Though LaTeX already takes care of good readability by choosing meaningful interline spacing, publishers might require different spacing.

我们将修改本章的第一个例子,在行间距上增加一半的行高:

We shall modify the very first example of this chapter by adding half of a line height to the line spacing:

  1. 使用此命令扩展示例的序言:

    \usepackage[onehalfspacing]{setspace}

  2. Extend the preamble of our example with this command:

    \usepackage[onehalfspacing]{setspace}

  3. 编译代码以查看更改:
  4. Compile the code to see the change:
图 3.14 – 额外的行间距

图 3.14 – 额外的行间距

Figure 3.14 – Additional interline spacing

我们加载了setspace包来调整行间距。我们提供了选项onehalfspacing,它增加了整个文档的行高一半的间距。

We loaded the setspace package to adjust the line spacing. We provided the option onehalfspacing, which increases the spacing by half of a line height for the whole document.

setspace包理解三个选项

The setspace package understands three options:

  • 单间距是默认值。不会插入额外的空间。文本将使用 LaTeX 的默认行间距排版,大约是行高的 20%。
  • singlespacing is the default. No additional space will be inserted. The text will be typeset with LaTeX's default interline spacing, which is about 20 percent of the line height.
  • onehalfspacing表示一个半间距,如您在我们的示例中所见。
  • onehalfspacing means one-and-a-half spacing, as you can see in our example.
  • doublespacing可用于更大的间距;连续文本行的基线之间的距离是单行的两倍。
  • doublespacing can be used for even more spacing; the distance between the baselines of successive text lines would be twice as high as a single line.

用排字工的行话来说,距离在连续文本的基线之间行称为leading

In typesetter's jargon, the distance between the baselines of consecutive text lines is called leading.

现在我们已经完成了整个文档的设计,让我们最后添加一个目录。

Now that we have finished designing a whole document, let's finally add a table of contents.

创建目录

Creating a table of contents

一本书通常开始有一个目录,所以让我们根据我们的编号标题创建一个:

A book commonly begins with a table of contents, so let's create one based on our numbered headings:

  1. 在我们之前的文档中,让我们删除选项landscapetwocolumn
  2. In our previous document, let's remove the options landscape and twocolumn.
  3. 移除setspace包,即删除这一行:

    \usepackage[onehalfspacing]{setspace}

  4. Remove the setspace package, that is, delete this line:

    \usepackage[onehalfspacing]{setspace}

  5. \begin{document}之后添加命令\tableofcontents

    我们的代码现在应该是这样的:

    \documentclass[a4paper,12pt]{book}

    \usepackage[english]{babel}

    \usepackage{盲文}

    \usepackage[a4paper, inner=1.5cm, outer=3cm, top=2cm,

    bottom=3cm, bindingoffset=1cm]{geometry}

    \开始{文档}

    \目录

    \chapter{探索页面布局}

    在本章中,我们将学习页面的布局。

    \section{一些填充文字}

    \盲文

    \section{更多填充文本}

    更多虚拟文本将随之而来。

    \subsection{大量填充文字}

    \盲文[10]

    \end{文档}

  6. Add the command \tableofcontents right after \begin{document}.

    Our code shall now look like this:

    \documentclass[a4paper,12pt]{book}

    \usepackage[english]{babel}

    \usepackage{blindtext}

    \usepackage[a4paper, inner=1.5cm, outer=3cm, top=2cm,

    bottom=3cm, bindingoffset=1cm]{geometry}

    \begin{document}

    \tableofcontents

    \chapter{Exploring the page layout}

    In this chapter we will study the layout of pages.

    \section{Some filler text}

    \blindtext

    \section{A lot more filler text}

    More dummy text will follow.

    \subsection{Plenty of filler text}

    \blindtext[10]

    \end{document}

  7. 编译代码两次。之后,输出的第一页将包含此表:
  8. Compile the code twice. Afterward, the first page of your output will contain this table:
图 3.15 – 目录

图 3.15 – 目录

Figure 3.15 – Table of Contents

命令\tableofcontents告诉 LaTeX 生成并打印目录。期间在一次排版运行中,LaTeX 将标题写入文件扩展名为.toc的辅助文件中。\tableofcontents命令读取.toc文件以打印目录。

The command \tableofcontents tells LaTeX to produce and to print a table of contents. During a typesetting run, LaTeX writes the headings into an auxiliary file with the file name extension .toc. The \tableofcontents command reads that .toc file in for printing the table of contents.

LaTeX 排版过程是线性的;它从代码的开头运行到结尾。\tableofcontents命令在开头,标题在后面。这就是为什么我们必须排版两次:

The LaTeX typesetting process is linear; it runs from the start to the end of the code. The \tableofcontents command comes at the beginning, and the headings come later. That's why we had to typeset twice:

  1. 在第一次运行中,\tableofcontents不知道任何标题,目录保持为空。在继续运行的同时,LaTeX 将标题放入.toc文件中。
  2. In the first run, \tableofcontents did not know any headings and the table of contents stayed empty. While continuing to run, LaTeX put the headings into the .toc file.
  3. 在第二次运行中,\tableofcontents找到并读取.toc文件以打印内容。
  4. In the second run, \tableofcontents found and read the .toc file to print the contents.

记住这一点以备后用:当您更改标题并编译文档时,您可以看到文本中的更改。但是目录将在下一次编译器运行时得到这个改变。

It's good to keep that in mind for later: when you change a heading and compile the document, you can see the change in the text. But the table of contents will get this change in the next compiler run.

目录条目由分段命令创建。我们使用了\chapter\section\subsection,并且每个都有一个条目。

The table of contents entries are created by the sectioning commands. We used \chapter, \section, and \subsection, and we've got an entry for each.

标题可能很长;它可以跨越两行或更多行。在那种情况下,我们可能希望缩短其相应的目录条目。让我们看看如何。

A heading might be very long; it could span over two or more lines. In that case, we might wish to shorten its corresponding table of contents entry. Let's see how.

我们可以使用可选的部分命令的参数以生成较短的条目,与实际标题不同。让我们通过在方括号中插入较短的标题来编辑图 3.15中所示的示例:

We can use the optional arguments of the section commands to produce shorter entries, different from the actual headings. Let's edit the example shown in Figure 3.15 by inserting shorter titles in square brackets:

\chapter[页面布局]{探索页面布局}

\chapter[Page layout]{Exploring the page layout}

\section[填充文字]{一些填充文字}

\section[Filler text]{Some filler text}

\section[More]{更多填充文字}

\section[More]{A lot more filler text}

\subsection[Plenty]{大量填充文本}

\subsection[Plenty]{Plenty of filler text}

编译示例两次。您会看到标题保持不变,但目录已更改:

Compile the example twice. You will see that the headings stay the same, but the table of contents has changed:

图 3.16 – 缩短的目录条目

图 3.16 – 缩短的目录条目

Figure 3.16 – Shortened table of contents entries

除了生成标题的强制参数外,每个分段命令都理解一个可选参数。如果给出了一个可选参数,它将被用来代替目录条目的强制性标题。

Besides the mandatory argument producing the heading, each sectioning command understands an optional argument. If an optional argument is given, it will be used instead of the mandatory heading for the contents table entry.

第 8 章列出内容和参考文献中,我们将进一步了解这一点并学习如何进一步自定义目录。让我们再看看bookreportarticle的分段命令。这些基类中有七个级别:

In Chapter 8, Listing Content and References, we shall take a further look at this and learn how to further customize the table of contents. Let's look again at the sectioning commands of book, report, and article. There are seven levels in those base classes:

  • \part:用于将文档划分为主要单元。其他部门单位的编号独立于\part。部分标题将在书籍报告文档中使用整页。
  • \part: That's for dividing the document into major units. The numbering of other sectional units is independent of \part. A part heading will use a whole page in book and report documents.
  • \chapter:给出一个大标题,将从新页面开始,在书籍类和报告类中可用。
  • \chapter: Gives a large heading that will start at a new page, available in the book class and in the report class.
  • \section\subsection\subsubsection:它们给出粗体标题,并且在所有三个类中都可用。
  • \section, \subsection, and \subsubsection: They give bold headings, and they are available in all three classes.
  • \段落\子段落h:在所有三个类别中也可用,它们会产生一个插入标题。这意味着标题直接进入正文;标题和后面的文字之间没有换行符。此外,它是一个分段命令,不应与普通文本段落混淆。
  • \paragraph and \subparagraph: Also available in all three classes, they produce a run-in heading. That means the heading runs straight into the text; there's no line break between the heading and the following text. Also, it's a sectioning command, and should not be confused with common text paragraphs.

\part外,所有分段命令都会重置层次结构中下一级的部分的计数器。例如,\chapter重置节计数器。这样,各节将按章编号。

Except \part, all sectioning commands reset the counter of the section that's one level below in the hierarchy. For instance, \chapter resets the section counter. This way, the sections will be numbered per chapter.

综上所述,这样的分节命令简单易用,而且作用很大:

To sum up, such sectioning commands are easy to use and they do a lot:

  • \part\chapter在标题前导致分页。
  • \part and \chapter cause a page break before the heading.
  • 所有这些都生成一个数字和一个表示,其中一些取决于更高级别的计数器(例如,第 2 章的第 1 节将生成 2.1)。
  • All generate a number and a presentation for it, some depending on the higher-level counters (for example, Section 1 of Chapter 2 would generate 2.1).
  • 除了\part,他们重置了下一级分区单元的计数器,使下一级单元从 1 开始。
  • Except \part, they reset the counter of the next-level sectional unit so that the lower-level unit will start with 1.
  • 他们生成目录条目。
  • They produce a table of contents entry.
  • 它们格式化标题,通常是粗体,它们越大,它们在层次结构中的位置就越高。
  • They format the heading, usually bold-faced, and the larger they are, the higher they are in the hierarchy.
  • 他们在内部保存标题以便在页眉中使用它们。
  • They save headings internally for using them in a page header.

所有分段命令都提供星号形式,如下所示:

All sectioning commands provide a starred form, as follows:

\section*{标题}

\section*{title}

如果您使用此表格,编号将被抑制,目录或标题中不会有条目。查看示例中的标题内容;这实际上是由\tableofcontents宏中的\chapter*排版的。

If you use this form, the numbering will be suppressed and there won't be an entry in the table of contents or in a header. Look at the heading Contents in our example; this has actually been typeset by \chapter* inside the \tableofcontents macro.

概括

Summary

在本章中,我们了解了如何设计文档的整体布局。

In this chapter, we have worked out how to design the overall layout of a document.

具体来说,我们学习了如何选择页面尺寸、页边距和方向。我们知道如何切换到两列布局以及如何调整行间距。此外,我们现在能够自定义页眉和页脚、添加脚注以及向我们的文档添加目录。

Specifically, we learned about choosing page dimensions, margins, and orientation. We know how to switch to a two-column layout and how to adjust line spacing. Furthermore, we are now able to customize headers and footers, add footnotes, and add a table of contents to our document.

此外,我们还介绍了一些一般主题,例如通过选择文档类选项和包选项以及通过重新定义现有命令来更改文档属性。

Furthermore, we covered some general topics, such as changing document properties by choosing document class options and package options and by redefining existing commands.

现在是时候处理更多的文本结构了。在下一章中,我们将学习如何创建列表以易于阅读的方式呈现文本。

Now it's time to deal with further text structures. In the next chapter, we shall learn how to create lists to present text in an easy-to-read way.

第 4 章:创建列表

Chapter 4: Creating Lists

以列表的形式排列文本对读者非常友好。您可以在易于调查的清晰结构中展示几个关键点。通常使用三种类型的列表:

Arranging text in the form of a list can be very reader-friendly. You can present several key points in a clear structure that is easy to survey. Commonly, three types of lists are used:

  • 项目符号列表,强调从文本中脱颖而出的几个要点
  • Bulleted lists, to emphasize several points standing out from the text
  • 枚举列表,按顺序呈现点
  • Enumerated lists, to present points in an order
  • 定义列表,以结构化的方式解释几个要点
  • Definition lists, to explain several points in a structured way

在本章中,我们将学习如何创建这样的列表。我们将介绍以下内容:

In this chapter, we shall learn how to create such lists. We will cover the following:

  • 建筑清单
  • Building lists
  • 自定义列表
  • Customizing lists

首先,我们将学习如何创建这些列表,然后在本章后面,我们将了解如何自定义它们。

First, we will learn how to create these lists, and then later in the chapter, we will see how to customize them.

技术要求

Technical requirements

您的计算机上需要有 LaTeX,或者您可以使用 Overleaf。您还可以在本书的网页上在线运行所有示例:https ://latexguide.org/chapter-04 。

You need to have LaTeX on your computer, or you can use Overleaf. You can also run all examples online on the book's web page: https://latexguide.org/chapter-04.

代码在 GitHub 上可用: https: //github.com/PacktPublishing/LaTeX-Beginner-s-Guide-2nd-Edition-/tree/main/Chapter_04_-_Creating_Lists

The code is available on GitHub: https://github.com/PacktPublishing/LaTeX-Beginner-s-Guide-2nd-Edition-/tree/main/Chapter_04_-_Creating_Lists.

在本章中,我们将使用以下 LaTeX 包:enumitemlayoutsparalist

In this chapter, we will use the following LaTeX packages: enumitem, layouts, and paralist.

建筑清单

Building lists

我们将从由要点构成的无序列表。在本节的后面,我们将处理按数字或字符枚举的有序列表,然后我们将继续解释关键字和事实的列表。

We will start with unordered lists that are structured by bullet points. Later in this section, we will deal with ordered lists that are enumerated by numbers or characters, and then we will continue with lists of explained keywords and facts.

创建项目符号列表

Creating a bulleted list

我们将开始用最简单的列表。它只包含没有数字的项目。每个项目都用项目符号标记。这样,与段落中文本中的长句相比,我们可以以更具可读性的方式组织关键点列表。

We shall start with the simplest kind of list. It contains just the items without numbers. Each item is marked by a bullet. That way, we can organize a list of key points in a much more readable way compared to a long sentence within text in a paragraph.

让我们创建一个我们在上一章中了解的包列表。按照以下步骤构建项目符号列表:

Let's create a list of packages that we got to know in the previous chapter. Follow these steps to build a bullet list:

  1. 使用一些介绍文本创建一个新文档:

    \文档类{文章}

    \开始{文档}

    \section*{有用的包}

    LaTeX 提供了几个包来设计

    布局:

  2. Create a new document with some introduction text:

    \documentclass{article}

    \begin{document}

    \section*{Useful packages}

    LaTeX provides several packages for designing the

    layout:

  3. 现在使用itemize环境和\item命令编写列表:

    \begin{逐项}

      \项目几何

      \项目类型区域

      \项目花式HDR

      \item scrpage-scrlayer

      \项目设置空间

    \结束{逐项}

  4. Now write the list, using an itemize environment and \item commands:

    \begin{itemize}

      \item geometry

      \item typearea

      \item fancyhdr

      \item scrpage-scrlayer

      \item setspace

    \end{itemize}

  5. 那很简单。现在我们可以结束文档了:

    \end{文档}

  6. That was easy. Now we can end the document:

    \end{document}

  7. 单击Typeset并查看输出:
  8. Click on Typeset and have a look at the output:
图 4.1 – 项目符号列表

图 4.1 – 项目符号列表

Figure 4.1 – A bulleted list

我们从一个标题开始,然后是一些文本。对于实际列表,我们使用了一个环境称为itemize。作为我们已经在第 2 章格式化文本和创建宏中了解了环境,\begin{itemize}启动它,\end{itemize}结束它。\item命令告诉 LaTeX 它将向列表中添加一个新项目。\item仅在列表中有效。每个项目都可以包含任意长度的文本,甚至可以包含段落分隔符。嗯,这很容易。

We began with a heading followed by some text. For the actual list, we used an environment called itemize. As we have already learned about environments in Chapter 2, Formatting Text and Creating Macros, \begin{itemize} starts it and \end{itemize} ends it. The \item command tells LaTeX that it will add a new item to the list. \item works only within a list. Each item can contain text of any length and even paragraph breaks. Well, that's pretty easy.

当列表变长时,我们可以通过划分它来使其更清晰。我们可以在列表下创建列表。建议使用不同的项目符号来轻松区分列表级别。LaTeX 会自动为我们做这件事。

When a list gets longer, we could make it clearer by dividing it. We can create lists under a list. It's advisable to use different bullets to differentiate between the list levels easily. LaTeX does this for us automatically.

我们将通过引入主题类别来完善前面示例中的包列表。为此,请按照下列步骤操作:

We shall refine our package list from the previous example by introducing topic categories. To do that, follow these steps:

  1. 按照以下方式改进我们示例的上述突出显示的逐项环境:为每个主题制作一个逐项列表,并使其成为\item点的一部分。我们之前示例中步骤 2中的列表代码现在应变为:

    \begin{逐项}

      \item 页面布局

        \begin{逐项}

          \项目几何

          \项目类型区域

        \结束{逐项}

      \item 页眉和页脚

        \begin{逐项}

          \项目花式HDR

          \item scrpage-scrlayer

        \结束{逐项}

      \item 行距

        \begin{逐项}

          \项目设置空间

        \结束{逐项}

    \结束{逐项}

    注意我们小心地关闭了每个环境。

  2. Refine the aforementioned highlighted itemize environment of our example in the following way: make an itemize list for each topic, and let it be part of an \item point. The list code from step 2 in our previous example shall now become this:

    \begin{itemize}

      \item Page layout

        \begin{itemize}

          \item geometry

          \item typearea

        \end{itemize}

      \item Headers and footers

        \begin{itemize}

          \item fancyhdr

          \item scrpage-scrlayer

        \end{itemize}

      \item Line spacing

        \begin{itemize}

          \item setspace

        \end{itemize}

    \end{itemize}

    Note that we carefully closed each environment.

  3. 编译文档以查看新列表:
  4. Compile the document to see the new list:
图 4.2 – 具有两个级别的项目符号列表

图 4.2 – 具有两个级别的项目符号列表

Figure 4.2 – A bulleted list with two levels

我们使用列表作为列表中\item点的一部分。那方式,我们嵌套列表。最多可以有四个级别;否则,LaTeX 会停止并打印出一条错误消息,上面写着! LaTeX 错误:嵌套太深。正如我们所见,第一层用项目符号标记,第二层用宽破折号标记。第三级项目将以星号符号*开头。第四层和最后一层将由一个居中的点标记。

We used lists as part of an \item point inside a list. That way, we nested lists. Up to four levels are possible; otherwise, LaTeX would stop and print out an error message that says ! LaTeX Error: Too deeply nested. As we saw, the first level is marked by a bullet, and the second by a wide dash. A third level item would start with an asterisk symbol, *. The fourth and last level would be marked by a centered dot.

很少使用深度嵌套的列表;如此复杂的结构可能难以阅读。在这种情况下,修改文本结构或至少拆分列表可能是个好主意。

Deeply nested lists are rarely used; such complicated structures might be hard to read. In such cases, it could be a good idea to revise the text structure or at least split the list.

在我们自己的这个例子的源代码中,我们在itemize环境中缩进了每一行。因此,如果在周围的itemize环境中有另一个itemize环境,则\item行会更加缩进。这样,我们就可以看到我们处于哪个级别的嵌套环境中。没有必要这样做,但是在环境中适当的缩进有助于维护代码结构,因为我们可以一目了然地看到环境的开始和结束位置。在环境中缩进源代码行通常是一个很好的习惯。您还可以将代码行缩进到向自己表明它属于某个父行,就像我们在这里对跨越多行的\item点所做的那样。

In our own source code of this example, we indented each line within an itemize environment. So, if there's another itemize environment within a surrounding itemize environment, the \item lines are even more indented. That way, we can see which level of nested environments we are in. It's not necessary to do this, but proper indentation within environments helps in maintaining the code structure, as we can see with a glance where an environment begins and where it ends. Indenting source code lines within an environment is a very good habit in general. You can also indent code lines to indicate to yourself that it belongs to some parent line, as we did here with \item points that spanned over several lines.

通过缩进给你的代码一个结构

Give your code a structure by indenting

使用空格字符或制表符缩进源代码大大提高了代码的可读性。它不会影响输出,因为 LaTeX 将代码行中的多个空白字符视为单个空白字符。

Indenting source code with space characters or tab characters improves the readability of the code very much. It won't affect the output because LaTeX treats multiple whitespace characters in a code line as a single whitespace character.

在下一节中,我们将看到如何按特定顺序列出关键点并对其进行编号。

In the next section, we will see how to list key points in a specific order and number them.

构建枚举列表

Building an enumerated list

项目符号如果项目的顺序无关紧要,列表很有用。然而,如果顺序是必不可少的,我们可以通过给它们编号并创建一个排序列表来组织这些项目。这将使读者很容易理解我们的想法。

Bulleted lists are useful if the order of the items doesn't matter. However, if the order is essential, we could organize the items by giving them numbers and creating a sorted list. That would allow the reader to follow our thoughts easily.

让我们准备一个使用编号列表设计页面布局的小型分步教程。按着这些次序:

Let's prepare a tiny step-by-step tutorial for designing the page layout using a numbered list. Follow these steps:

  1. 打开一个新文档并输入以下代码:

    \文档类{文章}

    \开始{文档}

    \开始{枚举}

      \item 通过选项指定纸张大小

            文档类

      \item 使用一个确定边距尺寸

            这些包:

        \begin{逐项}

          \项目几何

          \项目类型区域

        \结束{逐项}

      \item 自定义页眉和页脚

            这些包:

        \begin{逐项}

          \项目花式HDR

          \item scrpage-scrlayer

        \结束{逐项}

      \item 调整整个文档的行距

        \begin{逐项}

          \item 通过使用 setspace 包

          \item 或通过命令

                \verb|\linespread{因子}|

      \结束{逐项}

    \结束{枚举}

    \end{文档}

  2. Open a new document and enter the following code:

    \documentclass{article}

    \begin{document}

    \begin{enumerate}

      \item State the paper size by an option to the

            document class

      \item Determine the margin dimensions using one

            of these packages:

        \begin{itemize}

          \item geometry

          \item typearea

        \end{itemize}

      \item Customize header and footer by one

            of these packages:

        \begin{itemize}

          \item fancyhdr

          \item scrpage-scrlayer

        \end{itemize}

      \item Adjust the line spacing for the whole document

        \begin{itemize}

          \item by using the setspace package

          \item or by the command

                \verb|\linespread{factor}|

      \end{itemize}

    \end{enumerate}

    \end{document}

  3. 单击排版生成指令:
  4. Click on Typeset to generate the instructions:
图 4.3 – 带有项目符号列表的编号列表

图 4.3 – 带有项目符号列表的编号列表

Figure 4.3 – A numbered list with bulleted lists

我们用了突出显示的代码行中的枚举环境。除了名称,我们使用它就像itemize环境一样;每个列表项都由\item命令引入。不同之处在于我们枚举环境中的每个\item行都有编号,而不是前面只有一个要点。同样,我们嵌套了两个列表,只是这一次,列表是不同类型的。混合嵌套可以超过四层,但每种类型的列表最多可以嵌套四层,而混合列表通常有六层。

We used an enumerate environment in the highlighted code lines. Except for the name, we use it just like the itemize environment; each list item is introduced by the \item command. The difference is that every \item line in our enumerate environment is numbered instead of just having a bullet point in front. Again, we nested two lists, just this time, the lists are of a different kind. Mixed nesting could go further than four levels, but four is the maximum for each type of list, and six in general for mixed lists.

枚举环境的默认编号方案如下:

The default numbering scheme for the enumerate environment is as follows:

  • 第一层:1., 2., 3., 4., …
  • First level: 1., 2., 3., 4., …
  • 第二级:(a),(b),(c),(d),......
  • Second level: (a), (b), (c), (d), …
  • 第三级:i., ii., iii., iv., …
  • Third level: i., ii., iii., iv., …
  • 第四级:A., B., C., D., …
  • Fourth level: A., B., C., D., …

\item可以有一个可选参数。如果你写\item[text],LaTeX 打印文本而不是数字或项目符号。这样,您可以为项目符号使用任何编号和任何符号。

\item can have an optional argument. If you write \item[text], LaTeX prints text instead of a number or a bullet. This way, you could use any numbering and any symbol for the bullet.

现在我们知道如何创建带有项目符号和枚举列表的列表,让我们看一下可用于呈现多个项目描述的列表类型。

Now that we know how to create lists with bullet points and enumerated lists, let's look at a list type that we can use to present descriptions of several items.

生成定义列表

Producing a definition list

我们应该继续第三种列表,即定义列表,也叫描述列表。在这里,每个列表项都由一个术语或短语及其描述组成。

We shall proceed to the third kind of list, namely, definition lists, also called description lists. Here, every list item consists of a term or a phrase followed by its description.

要构建示例,我们需要一些短语来处理。与本章的第一个示例一样,我们将创建一个包列表。这次,我们将添加每个包的描述。我们从https://ctan.org/topic/list中选择一些包,这是一个列表相关包的集合。这是为下一节“自定义列表”做准备,我们将在其中使用我们为以下示例中的列表选择的包。

To build an example, we need some phrases to work on. As in the first example of this chapter, we will create a list of packages. This time, we will add a description of each package. Let's choose some packages from https://ctan.org/topic/list, which is a collection of list-related packages. This is in preparation for the next section, Customizing lists, where we will work with the packages we chose for the list in the following example.

我们将写一个简短的概述来展示每个包的功能。按着这些次序:

We shall write a short overview to show the capabilities of each package. Follow these steps:

  1. 我们将使用描述环境。使用以下代码创建文档:

    \文档类{文章}

    \开始{文档}

    \begin{描述}

      \item[paralist] 提供紧凑列表和列表

        可以在段落中使用的版本,

        有助于自定义标签和布局。

      \item[enumitem] 控制标签

        以及各种列表中的长度。

      \item[mdwlist] 用于自定义描述

        列表,它甚至允许多行标签。

        它具有紧凑的列表和功能

        暂停和恢复。

      \item[desclist] 提供更多的灵活性

        定义列表。

      \item[multenum] 产生垂直枚举

        多列。

    \结束{描述}

    \end{文档}

  2. We will use a description environment. Create a document with the following code:

    \documentclass{article}

    \begin{document}

    \begin{description}

      \item[paralist] provides compact lists and list

        versions that can be used within paragraphs,

        helps to customize labels and layout.

      \item[enumitem] gives control over labels

        and lengths in all kind of lists.

      \item[mdwlist] is useful to customize description

        lists, it even allows multi-line labels.

        It features compact lists and the capability

        to suspend and resume.

      \item[desclist] offers more flexibility in

        definition list.

      \item[multenum] produces vertical enumeration in

        multiple columns.

    \end{description}

    \end{document}

  3. 单击排版以获取定义列表:
  4. Click on Typeset to get the definition list:
图 4.4 – 定义列表

图 4.4 – 定义列表

Figure 4.4 – A definition list

我们使用了描述环境与其他列表一样,只是我们在方括号中使用了\item的可选参数。在description环境中,\item被定义为可选参数将以粗体字体排版。

We used the description environment like the other lists, except that we used the optional argument of \item in square brackets. In the description environment, \item is defined such that the optional parameter will be typeset in the bold typeface.

如果我们将其与项目符号列表进行比较,项目符号已被粗体关键字替换。

If we compare it to a bulleted list, the bullets have been replaced with bold font keywords.

我们还可以更改列表的间距、项目符号类型和编号样式。让我们在下一节中看看这个。

We can also change the spacing of our lists, the bullet type, and the numbering style. Let's look at this in the next section.

自定义列表

Customizing lists

默认值列表的外观对于间距、缩进和符号是有意义的。然而,可能需要为枚举、项目符号或修改行间距或缩进使用另一种方案。一些包帮助我们节省空间,以及自定义符号。让我们从间距开始。

The default appearance of lists is meaningful regarding the spacing, indentation, and symbols. Nevertheless, it may be required to use another scheme for the enumeration, for the bullets, or to modify the line spacing or their indentation. Some packages help us to save space, as well as to customize the symbols. Let's start with the spacing.

获取紧凑列表

Getting compact lists

一个经常出现的问题是如何减少列表中的空间。LaTeX 的列表通常被认为过于宽敞。我们将看看如何实现它。

A frequently arising question is how to reduce the space in lists. LaTeX's lists are often regarded as being too spacious. We shall see how to implement that.

让我们缩小本教程中的列表。我们将删除列表项周围以及整个列表前后的空格。按着这些次序:

Let's shrink our list in this tutorial. We shall remove the whitespace around the list items and before and after the whole list as well. Follow these steps:

  1. 在生成图 4.3 的枚举列表示例中,添加paralist包并将enumerate替换为compactenum并将itemize 替换compactitem

    \文档类{文章}

    \usepackage{paralist}

    \开始{文档}

    \begin{compactenum}

      \item 通过选项说明纸张大小

            文档类

      \item 使用一个确定边距尺寸

            这些包:

      \begin{compactitem}

        \项目几何

        \项目类型区域

      \end{compactitem}

      \item 自定义页眉和页脚

            这些包:

      \begin{compactitem}

        \项目花式HDR

        \item scrpage-scrlayer

      \end{compactitem}

      \item 调整整个文档的行距

      \begin{compactitem}

        \item 通过使用 setspace 包

        \item 或者通过命令 \verb|\linespread{factor}|

      \end{compactitem}

    \end{compactenum}

    \end{文档}

  2. In our enumerated list example that produced Figure 4.3, add the paralist package and replace enumerate with compactenum and itemize with compactitem:

    \documentclass{article}

    \usepackage{paralist}

    \begin{document}

    \begin{compactenum}

      \item State the paper size by an option to

            the document class

      \item Determine the margin dimensions using one

            of these packages:

      \begin{compactitem}

        \item geometry

        \item typearea

      \end{compactitem}

      \item Customize header and footer by one

            of these packages:

      \begin{compactitem}

        \item fancyhdr

        \item scrpage-scrlayer

      \end{compactitem}

      \item Adjust the line spacing for the whole document

      \begin{compactitem}

        \item by using the setspace package

        \item or by the command \verb|\linespread{factor}|

      \end{compactitem}

    \end{compactenum}

    \end{document}

  3. 编译并比较间距:
    图 4.5 – 一个紧凑的列表

    图 4.5 – 一个紧凑的列表

  4. Compile and compare the spacing:

    Figure 4.5 – A compact list

  5. 现在为setspace扩展突出显示的列表项,如下所示:

        \item 通过使用 setspace 包和一个

              它的选项:

          \begin{inparaenum}

            \item 单行距

            \item onehalfspacing

            \item 双倍间距

          \end{inparaenum}

  6. Now extend the highlighted list item for setspace as follows:

        \item by using the setspace package and one

              of its options:

          \begin{inparaenum}

            \item singlespacing

            \item onehalfspacing

            \item double spacing

          \end{inparaenum}

  7. 编译查看行距主题的变化:
  8. Compile and look at the change in the line spacing subject:
图 4.6 – 段落中的列表

图 4.6 – 段落中的列表

Figure 4.6 – A list within a paragraph

paralist包_我们使用的提供了几个新的列表环境,旨在在段落内排版或以非常紧凑的外观设计。我们加载了这个包,并将标准环境替换为紧凑的对应环境,使用compactenum枚举,使用compactitem逐项列出。虽然其他语法相同,但新环境不会在列表前后产生额外的垂直空格。他们也不在列表项周围添加垂直空间。列表和项目使用与常规文本相同的行间距。最后,它看起来更紧凑并节省空间。在第3步中,我们使用了新的inparaenum环境,其中项目被枚举但保持在同一段落内。

The paralist package that we used provides several new list environments designed to be typeset within paragraphs or in a very compact look. We loaded this package and replaced the standard environments with their compact counterparts, enumerate with compactenum, and itemize with compactitem. While the other syntax is the same, the new environments don't produce additional vertical whitespace before and after a list. They also don't add vertical space around list items. Lists and items are used with the same line spacing as regular text. Finally, it looks much more compact and saves space. In step 3, we used the new inparaenum environment, where the items are enumerated but stay within the same paragraph.

对于每个标准环境,paralist添加了三个相应的环境。

For each standard environment, paralist adds three corresponding environments.

对于项目符号列表,它添加下列:

For bulleted lists, it adds the following:

  • compactitem : itemize环境的紧凑版本,在列表或其项目之前或之后没有任何垂直空间。
  • compactitem: Compact version of the itemize environment without any vertical space before or after the list or its items.
  • inparaitem:在段落中排版的逐项列表,在印刷品中很少见。
  • inparaitem: An itemized list typeset within a paragraph, rarely seen in print.
  • asparaitem:每个列表项的格式都像一个单独的普通 LaTeX 段落,但前面有一个要点。
  • asparaitem: Every list item is formatted like a separate common LaTeX paragraph but with a bullet point in front.

对于编号列表,它添加以下内容:

For numbered lists, it adds the following:

  • compactenum :枚举环境的紧凑版本,在列表或其项目之前或之后没有任何垂直空间。
  • compactenum: Compact version of the enumerate environment without any vertical space before or after the list or its items.
  • inparaenum:在段落中排版的枚举列表。
  • inparaenum: An enumerated list typeset within a paragraph.
  • asparaenum:每个列表项的格式都像一个单独的普通 LaTeX 段落,但有编号。
  • asparaenum: Every list item is formatted like a separate common LaTeX paragraph but numbered.

对于描述列表,它添加下列:

For description lists, it adds the following:

  • compactdesc :描述环境的紧凑版本,即列表及其项目前后没有额外的垂直空间。
  • compactdesc: Compact version of the description environment, that is, without additional vertical space before and after the list and its items.
  • inparadesc:段落内的描述列表。
  • inparadesc: A description list that's within a paragraph.
  • asparadesc:每个列表项的格式都像一个单独的普通 LaTeX 段落,带有粗体关键字,如在描述列表中一样,作为该段落的介绍文本。
  • asparadesc: Every list item is formatted like a separate common LaTeX paragraph, with the bold keyword, as in a description list, as the intro text for the paragraph.

现在我们已经自定义了间距,让我们看看项目符号和数字。

Now that we have customized the spacing let's look at bullets and numbers.

选择项目符号和编号格式

Choosing bullets and numbering format

跟随特定语言的习惯或特别的需求,我们可能希望使用罗马数字或字母来枚举列表;也可能需要括号或点。有些人可能更喜欢破折号而不是项目符号。enumitem包提供了复杂的功能实现这些要求。

To follow language-specific habits or particular requirements, we might wish to enumerate lists by using Roman numbers or alphabets; parentheses or dots might also be required. Some may prefer dashes instead of bullets. The enumitem package provides sophisticated features to implement such requirements.

让我们更改编号方案。我们将使用带圆圈的字母按字母顺序对列表进行编号。此外,我们将用破折号替换项目符号。为此,请按照下列步骤操作:

Let's change the numbering scheme. We shall number a list alphabetically using circled letters. Furthermore, we will replace bullets with dashes. To do that, follow these steps:

  1. 我们现在使用的是enumitem包,而不是paralist。我们将远离“紧凑”环境,因此我们返回到标准列表表示法。尽管如此,我们想要有袖珍的列出并将nosep参数添加到列表:

    \文档类{文章}

    \usepackage{枚举}

    \setlist{nosep}

    \setitemize[1]{标签=---}

    \setenumerate[1]{label=\textcircled{\scriptsize\Alph*},

        字体=\sffamily}

    \开始{文档}

    \开始{枚举}

      \item 通过选项指定纸张大小

            文档类

      \item 使用以下之一确定边距尺寸

            这些包:

        \begin{逐项}

        \项目几何

        \项目类型区域

      \结束{逐项}

      \item 通过其中之一自定义页眉和页脚

            包裹:

      \begin{逐项}

        \项目花式HDR

        \item scrpage-scrheader

      \结束{逐项}

      \item 调整整个文档的行距

      \begin{逐项}

        \item 通过使用 setspace 包

        \item 或者通过命令 \verb|\linespread{factor}|

      \结束{逐项}

    \结束{枚举}

    \end{文档}

  2. Instead of paralist, we are now using the enumitem package. We will turn away from the "compact" environments, so we return to the standard list notation. Still, we want to have compact lists and add the nosep parameter to lists:

    \documentclass{article}

    \usepackage{enumitem}

    \setlist{nosep}

    \setitemize[1]{label=---}

    \setenumerate[1]{label=\textcircled{\scriptsize\Alph*},

        font=\sffamily}

    \begin{document}

    \begin{enumerate}

      \item State the paper size by an option to the

            document class

      \item Determine the margin dimensions using one of

            these packages:

        \begin{itemize}

        \item geometry

        \item typearea

      \end{itemize}

      \item Customize header and footer by one of these

            packages:

      \begin{itemize}

        \item fancyhdr

        \item scrpage-scrheader

      \end{itemize}

      \item Adjust the line spacing for the whole document

      \begin{itemize}

        \item by using the setspace package

        \item or by the command \verb|\linespread{factor}|

      \end{itemize}

    \end{enumerate}

    \end{document}

  3. 点击排版查看输出:
    图 4.7 – 定制的枚举列表

    图 4.7 – 定制的枚举列表

  4. Click on Typeset and check the output:

    Figure 4.7 – A customized enumerated list

  5. 在突出显示的代码行的正上方,插入以下行:

    \结束{枚举}

    \noindent\textbf{调整行间距:}

    \begin{枚举}[简历*]

  6. Right above the highlighted code line, insert the following lines:

    \end{enumerate}

    \noindent\textbf{Tweaking the line spacing:}

    \begin{enumerate}[resume*]

  7. 单击排版以查看更改:
  8. Click on Typeset to see the change:
图 4.8 – 恢复的列表

图 4.8 – 恢复的列表

Figure 4.8 – A list that's resumed

我们用过的枚举包_命令来指定列表属性。让我们仔细看看:

We used the enumitem package commands to specify list properties. Let's take a closer look:

  • \setlist{nosep} : \setlist设置对所有类型的列表有效的属性。在这里,我们指定nosep来实现类似于紧凑的paralist环境的非常紧凑的列表。该设置忽略了所有额外的垂直间距。
  • \setlist{nosep}: \setlist sets properties valid for all types of lists. Here, we specified nosep to achieve very compact lists analogous to the compact paralist environment. That setting omits all extra vertical spacing.
  • \setitemize[1]{label=--} : \setitemize修改项目符号列表的属性。在这里,我们选择了一个 em 破折号作为标签来获得一个领先的宽破折号。
  • \setitemize[1]{label=–--}: \setitemize modifies properties of bulleted lists. Here, we chose an em dash as the label to get a leading wide dash.
  • \setenumerate[1]{label=\textcircled{\scriptsize \Alph*},font=\sffamily} : \setenumerate设置对编号列表有效的属性。我们用它来设置标签和标签的字体。\Alph*命令表示用大写字母进行枚举。
  • \setenumerate[1]{label=\textcircled{\scriptsize \Alph*},font=\sffamily}: \setenumerate sets properties valid for numbered lists. We used it to set a label and a font for the label. The \Alph* command means enumeration in capital letters.

我们可以像使用resume*一样在本地使用这些选项。其他例子如下:

We can use those options locally as we did with resume*. Other examples are as follows:

  • \begin{itemize}[noitemsep]紧凑的项目符号列表,项目和段落之间没有任何额外的空间
  • \begin{itemize}[noitemsep] for a compact bulleted list without any additional space between items and paragraphs
  • \begin{enumerate}[label=\Roman*.,start=3]按 III.、IV. 等编号
  • \begin{enumerate}[label=\Roman*.,start=3] numbered by III., IV., and so on
  • \begin{enumerate}[label=\alph*)],nolistsep]用于编号为 a)、b)、c) 等的非常紧凑的列表
  • \begin{enumerate}[label=\alph*)],nolistsep] for a very compact list numbered a), b), c), and so on

标签命令将实现如下编号:

The labeling commands would achieve a numbering as follows:

  • \阿拉伯语* : 1, 2, 3, 4, …
  • \arabic*: 1, 2, 3, 4, …
  • \alph* : a, b, c, d, …
  • \alph*: a, b, c, d, …
  • \Alph* : A, B, C, D, …
  • \Alph*: A, B, C, D, …
  • \roman* : i, ii, iii, iv, …
  • \roman*: i, ii, iii, iv, …
  • \罗马* : I, II, III, IV, …
  • \Roman*: I, II, III, IV, …

*代表_的当前值列表柜台。可以根据需要使用括号和标点符号。在本书的后面,您将学习如何在成千上万的标签和项目符号符号之间进行选择。

The * stands for the current value of the list counter. Parentheses and punctuation may be used as required. Later in the book, you will learn to choose between thousands of symbols for labels and bullets.

甚至还有一个简短的形式;如果您使用shortlabels选项加载enumitem包,您可以使用紧凑的语法,例如\begin{enumerate}[(i)] , \begin{enumerate}[(1)]其中1 , a , A , i分别代表\arabic*\alph*\Alph*\roman*\Roman*。这样可以快速轻松地进行定制。但是,请考虑使用全局命令来保持格式一致。

There's even a short form; if you load the enumitem package with the shortlabels option, you may use a compact syntax such as \begin{enumerate}[(i)] , \begin{enumerate}[(1)] where 1, a, A, i, and I stand for \arabic*, \alph*, \Alph*, \roman*, and \Roman*, respectively. This allows customization quickly and easily. However, consider using global commands to keep formatting consistent.

当我们使用编号列表时,我们可能想停止它,写一些文本,然后继续它。让我们看看如何做到这一点。

When we use a numbered list, we may want to stop it, write some text, and continue it. Let's see how to do that.

暂停和继续列表

Suspending and continuing lists

第 3 步我们的在生成图 4.8的示例中,我们中断了列表。我们继续编写常规文本,直到我们使用\begin{enumerate}[resume*]重新启动列表。resume选项告诉enumitem使用下一个数字继续列表加星标的resume*变体使用与以前相同的格式。

In step 3 of our example that produced Figure 4.8, we interrupted the list. We continued writing regular text until we restarted the list by using \begin{enumerate}[resume*]. The resume option tells enumitem to continue the list with the next number. The starred resume* variant does it with the same formatting as before.

LaTeX 的列表具有有意义的布局。但是,有时您可能想要修改此布局,例如更改页边距或项目缩进。所有布局尺寸都由 LaTeX 宏决定,即所谓的长度。

LaTeX's lists have a meaningful layout. However, there might be occasions when you would like to modify this layout, such as changing the margins or the item indentation. All layout dimensions are determined by LaTeX macros, so-called lengths.

有一个非常适合可视化布局的包,它提供了这些长度宏。这叫做布局。让我们用它来检查 LaTeX 的列表维度。我们将使用这个小的文档:

There's a package that is really great for visualizing layouts, which presents these length macros. It's called layouts. Let's use it to examine LaTeX's list dimensions. We will use this small document:

\documentclass[12pt]{文章}

\documentclass[12pt]{article}

\usepackage{布局}

\usepackage{layouts}

\开始{文档}

\begin{document}

\列表图

\listdiagram

\end{文档}

\end{document}

通过简单的排版,我们将得到如下图:

By simply typesetting it, we will get the following diagram:

图 4.9 – 列表的布局

图 4.9 – 列表的布局

Figure 4.9 – The layout of lists

不是极好的?layouts包可以做的更多,您可以在https://texdoc.org/pkg/layouts的文档中阅读,或者在命令行运行texdoc layouts 。现在,我们将继续讨论列表的主题。

Isn't it fantastic? The layouts package can do even more, which you can read about in its documentation at https://texdoc.org/pkg/layouts or by running texdoc layouts at the command line. For now, we'll stay on the topic of lists.

使用 LaTeX \setlength命令自定义这些长度,例如\setlength{\labelwidth}{2cm}。将它们应用于单个列表和某些嵌套深度是很困难的。如果需要修改列表布局,enumitem包又派上用场了。我们可以使用它的命令,如\setlist和它的key=value接口来调整长度,如上图所示。

Use the LaTeX \setlength command to customize those lengths, for example, \setlength{\labelwidth}{2cm}. Applying them to individual lists and certain nesting depths is hard. If you need to modify the list layout, the enumitem package comes in handy again. We can use its commands such as \setlist and its key=value interface to adjust the lengths as you can see in the previous diagram.

例如,如果我们想去除 description 环境中列表项之间的空格并减少左边距,我们可以加载enumitem包并编写以下内容:

For example, if we would like to remove the space between list items in the description environment and to reduce the left margin, we could load the enumitem package and write the following:

\setdescription{itemsep=0cm,parsep=0cm,leftmargin=0.5cm}

\setdescription{itemsep=0cm,parsep=0cm,leftmargin=0.5cm}

请注意,我们不对键使用反斜杠。同样,\setitemize\setenumerate\setlist可用于微调。尝试自己赋值并测试影响在我们的例子中。如果您想了解更多信息,请查看https://texdoc.org/pkg/enumitem上的enumitem文档,或者在命令提示符下运行texdoc enumitem 。

Note we don't use the backslash for keys. Similarly, \setitemize, \setenumerate, and \setlist can be used for fine-tuning. Try assigning values by yourself and test the effect on our examples. If you would like to learn more, have a look at the enumitem documentation at https://texdoc.org/pkg/enumitem or by running texdoc enumitem at the command prompt.

概括

Summary

在本章中,我们了解了一种构建文本的新方法——列表。具体来说,我们学习了如何创建项目符号列表、编号列表和定义列表。此外,我们使用了此类列表的紧凑和自定义版本,包括间距调整以及中断和恢复。

In this chapter, we got to know a new way to structure our text—lists. Specifically, we learned how to create bulleted lists, numbered lists, and definition lists. Furthermore, we worked with compact and customized versions of such lists, including spacing adjustments and interrupting and resuming.

您可以将这些列表视为构建文本的另一种可能性。用它来阐明你的想法。

You may regard those lists as an additional possibility to structure your text. Use it to clarify your ideas.

在下一章中,我们将构建有关特定对齐方式的文本并使用表格。

In the next chapter, we will structure our text concerning specific alignment and work with tables.

第 5 章:包括图像

Chapter 5: Including Images

文档不仅包含文本。您可能希望包括用其他程序制作的图片、图表或绘图。在本章中,我们将学习如何以最佳质量和良好定位插入此类图像。

Documents do not only consist of text. You might wish to include pictures, diagrams, or drawings made with other programs. In this chapter, we will learn how to insert such images with optimal quality and good positioning.

我们现在将了解以下主题:

We will now learn about the following topics:

  • 包括图像
  • Including an image
  • 管理浮动图像
  • Managing floating images

到本章结束时,我们将知道如何准确地按照我们的需要在文本中定位图像。

By the end of this chapter, we will know how to position images within text exactly as we want.

技术要求

Technical requirements

您需要安装 LaTeX,或者您可以使用 Overleaf。您还可以在本书的网页https://latexguide.org/chapter-05上进行编辑和编译。

You need to have LaTeX installed, or you can use Overleaf. You can also edit and compile on the book's web page at https://latexguide.org/chapter-05.

本章的代码可在 GitHub 上找到,网址为https://github.com/PacktPublishing/LaTeX-Beginner-s-Guide-2nd-Edition-/tree/main/Chapter_05_-_Including_Images

The code for this chapter is available on GitHub at https://github.com/PacktPublishing/LaTeX-Beginner-s-Guide-2nd-Edition-/tree/main/Chapter_05_-_Including_Images.

在本章中,我们将使用以下 LaTeX 包:babelblindtextcapt-offloatgraphicxpdfpageswrapfig

In this chapter, we will use the following LaTeX packages: babel, blindtext, capt-of, float, graphicx, pdfpages, and wrapfig.

我们还将简要介绍这些包:afterpagecaptionepstopdfeso-picmicrotypeplaceinsrotatingsubcaptionsubfigsubfiguretextpos

We will also briefly talk about these packages: afterpage, caption, epstopdf, eso-pic, microtype, placeins, rotating, subcaption, subfig, subfigure, and textpos.

包括图像

Including an image

对于包括图像,标准包是称为graphicx。名称中的x表示它正在扩展原始但已过时的图形

For including images, the standard package is called graphicx. The x in the name means it's extending the original, but outdated, graphics package.

我们将创建一个简短的文档,在两个段落之间,我们想插入一张图片。我们可以借助以下步骤来做到这一点:

We will create a short document, and between two paragraphs, we would like to insert a picture. We can do so with the help of the following steps:

  1. 开始一个新文档并加载babelblindtext以打印一些填充文本,如下所示:

    \documentclass[a5paper]{文章}

    \usepackage[english]{babel}

    \usepackage{盲文}

    \usepackage{graphicx}

    \pagestyle{空}

    \开始{文档}

    \section{包括一张图片}

    \盲文

  2. Begin a new document and load babel and blindtext to print some filler text, as follows:

    \documentclass[a5paper]{article}

    \usepackage[english]{babel}

    \usepackage{blindtext}

    \usepackage{graphicx}

    \pagestyle{empty}

    \begin{document}

    \section{Including a picture}

    \blindtext

  3. 打开图形环境并声明\centering,如下所示:

    \开始{图}

      \定心

  4. Open a figure environment and declare \centering, as follows:

    \begin{figure}

      \centering

  5. 使用以文件名作为参数的\includegraphics命令。我们将使用example-image作为文件名,因为这是 TeX Live 中包含的示例图像。以下代码段说明了代码:

      \includegraphics[width=4cm]{示例图像}

  6. Use the \includegraphics command with the filename as the argument. We will use example-image as the filename since that's a sample image included with TeX Live. The code is illustrated in the following snippet:

      \includegraphics[width=4cm]{example-image}

  7. 设置标题,关闭图形环境,并以填充文本结束文档,如如下代码片段所示:

      \caption{测试图}

    \结束{图}

    \盲文

    \end{文档}

  8. Set a caption, close the figure environment, and end the document with filler text, as illustrated in the following code snippet:

      \caption{Test figure}

    \end{figure}

    \blindtext

    \end{document}

  9. 单击Typeset编译文档,并查看输出,您可以在以下屏幕截图中看到:
  10. Click on Typeset to compile the document, and have a look at the output, which you can see in the following screenshot:
图 5.1 – 文档中的图像

图 5.1 – 文档中的图像

Figure 5.1 – An image in a document

最多重要的命令是\includegraphics,我们在其中指定了一个文件名。LaTeX 加载此文件(如果存在);否则,它将显示错误。LaTeX 支持以下文件类型:

The most important command is \includegraphics, where we specified a filename. LaTeX loads this file if it exists; otherwise, it will show an error. LaTeX supports the following file types:

  • PNGJPGPDF如果直接编译为PDF ( pdfLaTeX )
  • PNG, JPG, and PDF if you directly compile to PDF (pdfLaTeX)
  • 如果编译为DVI并转换为PSPDF(传统 LaTeX),则为EPS
  • EPS if you compile to DVI and convert to PS and PDF (traditional LaTeX)

澄清一下,PS代表PostScriptEPS代表Encapsulated PostScript,而DVI代表Device Independent File Format。后者是第一个支持的输出格式TeX 和乳胶。你绝对必须知道PDF(代表Portable Document Format)和非常流行的图片格式PNGJPG,它们经常用于屏幕截图和照片。

To clarify, PS stands for PostScript, EPS stands for Encapsulated PostScript, and DVI stands for Device Independent File Format. The latter was the first output format to be supported by TeX and LaTeX. You definitely must know PDF (which stands for Portable Document Format) and the very popular picture formats, PNG and JPG,which are often used for screenshots and photos.

您不需要指定文件扩展名,因为 LaTeX 会自动添加它。将文件放入与文档相同的目录或指定完整或相对路径名,如下所示:

You don't need to specify a filename extension as LaTeX adds this automatically. Either put the file into the same directory as your document or specify a full or relative pathname, as follows:

\includegraphics{附录/图1}

\includegraphics{appendix/figure1}

在文件路径中,使用正斜杠字符 ( / );不要使用反斜杠字符 ( \ ),因为后者是 LaTeX 命令的开头。

In file paths, use forward slash characters (/); don't use backslash characters (\), as the latter begins a LaTeX command.

继续和将您选择的图片复制到您的文档目录中。给\includegraphics它的文件名,然后编译。LaTeX 以其原始大小嵌入图片。

Go ahead and copy a picture of your choice into your document directory. Give \includegraphics its filename, and compile. LaTeX embeds the picture with its original size.

在接下来的部分中,我们将看到如何选择图像文件类型并添加指定大小的图像,包括整个 PDF 页面,或将其放置在文本后面的背景中。

In the following sections, we will see how to choose an image file type and add an image of a specified size, including a whole PDF page, or place it in the background behind the text.

选择最佳文件类型

Choosing an optimal file type

如果你已经得到JPG、PNG 或 PDF 格式的最终​​图片,您可以使用此格式并将图片包含在文档中。更改图像格式不会提高质量。不过,在拍照之前,您可以自由选择文件格式。让我们看看如何决定使用哪种文件格式。

If you have already got the final picture in JPG, PNG, or PDF format, you can use this format and include the picture in your document. Changing the image format doesn't improve quality. Before taking the picture, though, you are free to choose a file format. Let's see how to decide which file format to use.

EPSPDF两种矢量图形格式。它们是可扩展的,而且都在高分辨率或放大时看起来不错。因此,只要有可能,PDF(或EPS)应该是首选格式——例如,当您从其他办公软件导出绘图或图表时。对于此类图形,矢量格式很常见。

EPS and PDF are both vector graphics formats. They are scalable, and both also look good at high resolution or if you zoom in. So, whenever possible, PDF (or EPS) should be the preferred format—for instance, when you export drawings or diagrams out of other office software. For such graphics, vector formats are common.

PNGJPG是位图格式,也称为光栅图形,通常用于照片。如果放大,您会注意到质量下降。PNG使用无损压缩,而JPG图片在保存时可能会降低质量。因此,如果您制作屏幕截图,请使用PNG ,或者如果您选择JPG,请确保没有丢失压缩。对于照片,建议使用JPG 格式以避免生成庞大的 PDF 文件。

PNG and JPG are bitmap formats, also called raster graphics, commonly used for photos. If you zoom in, you will notice a loss of quality. PNG uses lossless compression, whereas JPG pictures may lose quality when we save them. So, if you make screenshots, use PNG, or ensure that there's no loss compression if you choose JPG. For photos, JPG is recommended to avoid getting huge PDF files.

除了支持向量图形,EPSPDF都可能包含位图图形。它们也称为容器格式

Besides supporting vector graphics, both EPS and PDF may contain bitmap graphics. They are also called container formats.

有很多工具可以在图形格式之间进行转换。以下三个程序是有益的,TeX Live 和 MiKTeX 都包括它们:

There are a lot of tools to convert between graphic formats. The following three programs are beneficial, and both TeX Live and MiKTeX include them:

  • dvips将DVI文件转换为后记格式。
  • dvips converts DVI files to PostScript format.
  • ps2pdf转换PostScript 文件到PDF
  • ps2pdf converts PostScript files to PDF.
  • epstopdf将EPS文件转换为PDF,同名的 LaTeX 包。如果你用\usepackage加载它, epstopdf会即时执行它。
  • epstopdf converts EPS files to PDF, the LaTeX package with the same name. epstopdf does it on the fly if you load it with \usepackage.

这些是命令行工具。一些 LaTeX 编辑器使用它们提供从.tex.dvi、到.ps、然后到.pdf的单击编译。

These are command-line tools. Some LaTeX editors use them to provide single-click compiling from .tex to .dvi, to .ps, and then to .pdf.

epstopdf特别有用如果您必须包含 PostScript 图片并希望受益于pdfLaTeX功能,例如字体扩展和字符突出,可通过microtype访问。

epstopdf is especially useful if you have to include PostScript pictures and wish to benefit from pdfLaTeX features such as font expansion and character protrusion, accessible by microtype.

Inkscape、ImageMagick 和 GIMP 是功能强大的免费开源程序,可用于进一步处理图形。

Inkscape, ImageMagick, and GIMP are very capable free and open source programs for further working with graphics.

缩放图像

Scaling an image

添加时图片,您可以选择不同的尺寸。为此,让我们看一下\includegraphics的定义,如下所示:

When adding an image, you may choose a different size. For this, let's look at the definition of \includegraphics, as follows:

\includegraphics[键=值列表]{文件名}

\includegraphics[key=value list]{file name}

graphicx文档列出了所有键和可能的值这里是最流行的,然后\includegraphics做了什么:

The graphicx documentation lists all keys and possible values. Here are the most popular ones, and what \includegraphics does then:

  • width:调整到这个宽度。示例:宽度=0.9\textwidth
  • width: Resizing to this width. Example: width=0.9\textwidth.
  • height:调整到这个高度。示例:高度=3cm
  • height: Resizing to this height. Example: height=3cm.
  • scale:按此因子缩放。示例:比例=0.5
  • scale: Scaling by this factor. Example: scale=0.5.
  • angle:旋转这个角度。示例:角度=90
  • angle: Turning by this angle. Example: angle=90.

还有裁剪选项,但您可以使用任何图形软件轻松进行此类后处理。

There are also options for clipping, but you can easily do such postprocessing with any graphics software.

除了将图形旋转 90 度,您还可以使用sidewaysfigure环境旋转包(参见https://texdoc.org/pkg/rotating

Instead of turning a figure by 90 degrees, you could also use the sidewaysfigure environment of the rotating package (see https://texdoc.org/pkg/rotating).

包括整页

Including whole pages

我们怎样才能包括更广泛的图片还是高于文字区域?\includegraphics可以做到这一点,但 LaTeX 会抱怨宽度或大小,并可能将它们移到下一页。

How can we include pictures wider or higher than the text area? \includegraphics could do this, but LaTeX would complain about width or size and might move them to the next page.

使用pdfpages包,我们可以包含大图像甚至整个页面。pdfpages包提供了\includepdf命令,可以包含一个完整的页面甚至一次处理一个多页 PDF 文档。除了它的名字,它还可以包含PNGJPG文件,而不仅仅是PDF文件( https://texdoc.org/pkg/pdfpages上的文档没有提到)。

Using the pdfpages package, we can include large images and even whole pages. The pdfpages package provides the \includepdf command, which can include a complete page or even a multi-page PDF document at once. Despite its name, it can also include PNG and JPG files, not just PDF files (something the documentation at https://texdoc.org/pkg/pdfpages does not mention).

它的基本用法示例如下所示:

An example of its basic usage could look like this:

\usepackage{pdfpages}

\usepackage{pdfpages}

……

\includepdf[pages=-]{contract}%包括整个contract.pdf

\includepdf[pages=-]{contract}% include entire contract.pdf

\includepdf[pages=2-4]{spec}% 包含 spec.pdf 的第 2-4 页

\includepdf[pages=2-4]{spec}% include pages 2-4 of spec.pdf

一个常见的用途是将多个PDF文件组合成一个PDF文件。我们还可以使用pdfpages调整多个PDF页面的大小并将它们排列在一张纸上。

A common use is combining several PDF files into a single PDF file. We can also use pdfpages to resize several PDF pages and arrange them on a single sheet.

把图片放在文字后面

Putting images behind the text

你需要水印吗?背景图片?位于任意位置的文本框在页面上,最好不要干扰其他文本?eso -pic包确实这个给你

Do you need watermarks? Background images? Textboxes positioned at arbitrary positions on the page, preferably not interfering with other text? The eso-pic package does this for you.

LaTeX Cookbook中,您可以在第 2 章“调整文本”的文本绝对定位部分阅读有关如何执行此操作的分步示例。

In the LaTeX Cookbook, you can read a step-by-step example of how to do this in the Absolute positioning of text section in Chapter 2, Tuning the Text.

textpos包_提供了另一种方法。它是为在页面上的绝对位置放置带有文本或图形的框而开发的;请参阅https://texdoc.org/pkg/textpos

The textpos package offers another approach. It's developed for placing boxes with text or graphics at absolute positions on a page; see https://texdoc.org/pkg/textpos.

现在,我们来看看动态图像定位。

Now, we will take a look at dynamic image positioning.

管理浮动图像

Managing floating images

当一个页面发生中断时,可以中断常规文本以继续到下一页。但是自动分页不能分割图片。这就是 LaTeX 提供浮动环境的原因——即figure。这样的漂浮环境也是称为花车。LaTeX 可能会将其内容(包括标题)推送到适合页面布局和分页的位置。

When a page break occurs, regular text can be broken to continue onto the next page. However, the automatic page breaking cannot divide pictures. That's why LaTeX provides a floating environment—namely, figure. Such floating environments are also called floats. LaTeX may push their content, including captions, to a place suitable for page layout and page breaking.

我们现在将弄清楚如何处理这个问题。

We will now figure out how to deal with this.

图形环境采用影响图形最终位置的可选参数我们将在我们的图形示例中测试效果,如下所示:

The figure environment takes an optional argument affecting the final placement of the figure. We will test the effect in our graphics example, as shown here:

  1. 回到前面的图 5.1示例。这一次,在突出显示的行中添加ht选项(其中ht代表heretop),如下所示:

    \begin{图}[ht]

      \定心

      \includegraphics{示例图像}

      \caption{测试图}

    \结束{图}

  2. Go back to the previous example we had for Figure 5.1. This time, add the h and t options in the highlighted line (where h and t stands for here and top), as follows:

    \begin{figure}[ht]

      \centering

      \includegraphics{example-image}

      \caption{Test figure}

    \end{figure}

  3. 编译文档,并查看输出。它应该是这样的:
    图 5.2 – 文本中的图像

    图 5.2 – 文本中的图像

  4. Compile the document, and take a look at the output. It should look like this:

    Figure 5.2 – An image within the text

  5. 将突出显示行中的选项更改为!b(其中b代表底部),如下所示:

    \begin{图}[!b]

  6. Change the options in the highlighted line to !b (where b stands for bottom), as follows:

    \begin{figure}[!b]

  7. 再次编译。图形现在被迫浮动到底部,现在我们看到这个页面:
  8. Compile again. The figure is now forced to float to the bottom, and now we see this page:
图 5.3 – 页面底部的图像

图 5.3 – 页面底部的图像

Figure 5.3 – An image at the page bottom

通过增加一些代表放置选项的字符,我们可以强制图形出现在我们想要的任何地方。

By adding some characters standing for placement options, we could force the figure to appear wherever we want.

跨越文本列的数字

Spanning figures over text columns

有一个带星号的表格——即figure* ——在一个两列布局中,将一个图形放在一个单独的列中。在单列模式下,与非星号形式没有区别。

There is a starred form—namely, figure*—in a two-column layout that puts a figure into a single column. In one-column mode, there's no difference to the non-starred form.

现在让我们仔细看看人物的定位。我们将看到如何设置首选项来确定图形出现的位置,例如在页面的顶部或底部,如何强制立即输出,或至少限制浮动,以及如何将图像彼此相邻排列或在文本流中。

Let's now take a closer look at the positioning of figures. We will see how we can set a preference as to where figures will appear, such as at the top or bottom of pages, how to force the immediate output, or at least limit the floating, and how to arrange images next to each other or within the text flow.

了解放置选项

Understanding placement options

可选的figure环境的参数告诉 LaTeX 允许放置图形的位置。四个字母代表四个可能的位置,如下所示:

The optional argument of the figure environment tells LaTeX where it's allowed to place the figure. Four letters stand for four possible places, as outlined here:

  • h代表这里。该图可能会出现在我们在源代码中编写它的位置。
  • h stands for here. The figure may appear where we wrote it in the source code.
  • t代表顶部。允许将图形放在页面顶部。
  • t stands for top. Placing the figure at the top of a page is permitted.
  • b代表底部。该图可能出现在页面底部。
  • b stands for bottom. The figure may appear at the bottom of a page.
  • p代表页面。该图可以出现在单独的页面上,其中只能驻留浮动但不能驻留普通文本。
  • p stands for page. The figure can appear on a separate page, where only floats may reside but no normal text.

第五个选项可能会派上用场,如下所述:

A fifth option might come in handy, as outlined here:

  • 告诉 LaTeX 更加努力地忽略一些约束,从而简化放置。
  • ! tells LaTeX to try harder to ignore some constraints, easing the placement.

如果你不指定任何选项,LaTeX 都可以将图形放置在远处。新的 LaTeX 用户可能对此感到惊讶。指定更多选项将有助于尽可能接近它。最灵活的方法是使用[!htbp]放置,让图形无处不在。如果您不喜欢,您仍然可以考虑删除放置说明符。

If you don't specify any option, LaTeX can place the figure far away. New LaTeX users might be surprised by this. Specifying more options would help to put it as near as possible. The most flexible way is to use the [!htbp] placement, allowing the figure to go everywhere. You could still consider removing a placement specifier if you don't like it.

强制输出数字

Forcing the output of figures

如果你想停下来LaTeX 从放置浮点数开始,有一种方法可以做到这一点—— \clearpage命令结束当前页面并导致打印出所有已经定义的图形。您也可以使用\cleardoublepage,它的作用相同,但采用双面布局。它确保下一个非浮动页面是右侧页面。如有必要,它会插入一个空白页。

If you would like to stop LaTeX from putting the floats, there's a way to do this—the \clearpage command ends the current page and causes the printing out of all already defined figures. You can also use \cleardoublepage, which does the same but in a two-sided layout. It ensures that the next non-float page is a right-hand page. If necessary, it inserts a blank page.

立即结束页面可能不是最好的做法,因为这可能会在当前页面上留下很多空白空间。afterpage包为此提供了一个创造性的解决方案这个包允许\clearpage的执行被推迟到当前页面结束,如下所示:

Immediately ending the page might not be the best thing to do, as this could leave a lot of empty space on the current page. The afterpage package offers a creative solution to this. This package allows the execution of \clearpage to be deferred until the current page has ended, as shown here:

\usepackage{后页}

\usepackage{afterpage}

...

...

主体

body text

\afterpage{\clearpage}

\afterpage{\clearpage}

我们可能不需要经常使用afterpage包,因为我们可以在所需位置运行\clearpage命令,例如在一个部分的末尾。我们可以自动化那个案例。让我们在下一节中看看这个。

We may not need to use the afterpage package often, as we can just run a \clearpage command at the desired place, such as at the end of a section. We can automate that case. Let's look at this in the next section.

限制浮动

Limiting floating

人影可能会飘到很远的地方,甚至可能飘到另一个区域。placeins包提供一个有用的命令来限制浮动。如果您使用\usepackage{placeins}加载placeins并在您的某处写入\FloatBarrier文件,没有人影可以从它身边飘过。这个宏将浮点数保持在原位。

Figures may float far away, perhaps even into another section. The placeins package provides a useful command to restrict the floating. If you load placeins with \usepackage{placeins} and write \FloatBarrier somewhere in your document, no figure can float past it. This macro keeps floats in their place.

一个非常方便的防止浮动越过节边界的方法是声明选项,如下所示:

A very convenient way to prevent floats from crossing section boundaries is by stating the section option, as follows:

\usepackage[section]{placeins}

\usepackage[section]{placeins}

此选项会在每个部分的开头导致隐式\FloatBarrier 。另外两个选项(即上方下方)允许您降低限制,防止浮动出现在当前部分开头上方或下一部分开头下方。

This option causes an implicit \FloatBarrier at the beginning of each section. Two further options—namely, above and below—allow you to lower the restrictions, preventing floats from appearing above the start of the current section or below the beginning of the next section.

由于\chapter隐式使用\clearpage,因此数字不会出现在下一章中。

Figures don't float into the next chapter because \chapter implicitly uses \clearpage.

完全避免漂浮

Avoiding floating at all

你是否想要将图像准确放置在您想要的位置?显而易见的答案是:不要使用浮动图形环境。我们可以在没有图形环境的情况下使用\includegraphics。例如,我们可以通过执行以下操作来包含和居中图像:

Would you like to place an image exactly where you want it? The obvious answer is: don't use a floating figure environment. We can use \includegraphics without a figure environment. For example, we could include and center an image by doing the following:

\开始{中心}

\begin{center}

  \includegraphics[width=4cm]{示例图像}

  \includegraphics[width=4cm]{example-image}

\结束{中心}

\end{center}

不过,字幕适用于浮动环境,因此\caption命令在这里不起作用。如果你还想有一个标题,你可以使用\captionof命令。标题包、 KOMA - Script类和包装_提供那个命令,我们可以这样使用:

Captions are for floating environments, though, so a \caption command won't work here. If you still want to have a caption, you may use the \captionof command. The caption package, KOMA-Script classes, and the tiny capt-of package provide that command, which we can use in this way:

\usepackage{capt-of}% 或标题

\usepackage{capt-of}% or caption

……

\begin{minipage}{\linewidth}

\begin{minipage}{\linewidth}

  \定心

  \centering

  \includegraphics{示例图像}

  \includegraphics{example-image}

  \captionof{图}{测试图}

  \captionof{figure}{Test figure}

\end{小页面}

\end{minipage}

页面环境将图片和标题放在一起,因为在小页面环境中不会出现分页符。\captionof的定义与\caption相同,除了有一个额外的参数指定 float 类型 - 在本例中为figure,如以下代码片段所示:

The minipage environment keeps a picture and its caption together because no page break can occur in a minipage environment. The definition of \captionof is the same as \caption, except that there is an additional argument specifying the float type—in this case, figure, as illustrated in the following code snippet:

\captionof{图}[短文本]{长文本}

\captionof{figure}[short text]{long text}

请注意,如果混合使用真正的浮点数和固定数字,编号可能会出错。由于您无法从 LaTeX 的定位功能中获益,因此您必须注意页面是否仍被充分填充。

Be aware that the numbering could go awry if you mix real floats and fixed figures. As you don't benefit from LaTeX's positioning capabilities, you have to take care that pages are still adequately filled.

float包为此提供了一种方便且外观一致的方法它引入了H放置选项,使浮动出现在此处,如以下代码片段所示:

The float package provides a convenient and consistent-looking approach to this. It introduces the H placement option, causing the float to appear right there, as illustrated in the following code snippet:

\usepackage{浮动}

\usepackage{float}

……

\begin{图}[H]

\begin{figure}[H]

  \定心

  \centering

  \includegraphics{示例图像}

  \includegraphics{example-image}

  \caption{测试图}

  \caption{Test figure}

\结束{图}

\end{figure}

您可以在这两个选项之间进行选择。如果您想探索浮动包的其他功能,请加载它。否则,请考虑使用capt-of one-liner。假设您已经在使用caption包或 KOMA-Script 类,也许甚至没有必要这样做。

You may choose between these two options. If you wish to explore additional features of the float package, load it. Otherwise, consider using the capt-of one-liner. Perhaps even that is unnecessary, assuming that you're already using the caption package or a KOMA-Script class.

排列多张图片

Arranging several images

用于分组几个单个图中带有标题的子图,您可以选择几个支持包,概述如下:

For grouping several subfigures with captions within a single figure, there are several supporting packages you can choose from, outlined as follows:

  • subcaption是一个包含subcaptions 的subfigures 的包,属于caption包。(如果您在文档中使用超链接,请选择subcaption因为这更好地支持超链接。对于超链接,另请参阅第 12 章进一步增强您的文档。)
  • subcaption is a package for subfigures with subcaptions and belongs to the caption package. (If you use hyperlinks in a document, choose the subcaption package since this supports hyperlinks better. For hyperlinks, also see Chapter 12, Enhancing Your Documents Further.)
  • 子图是一个精巧的封装,支持小数字的包容。它负责单个浮动中的定位、标签和字幕。
  • subfig is a sophisticated package, supporting the inclusion of small figures. It takes care of positioning, labeling, and captioning within single floats.
  • 子图还在可用于此目的,但我们可以认为它已过时,因为subfig出现了。
  • subfigure is still available for this purpose, but we can consider it obsolete since subfig has appeared.

不要将其中两个包一起加载。通常,加载两个服务于相同目的的包会导致冲突。

Don't load two of these packages together. In general, loading two packages that serve the same purpose can lead to conflicts.

对于对齐图像、堆叠图像或将它们放置在网格中,在LaTeX Cookbook 的4 章使用图像中有解释的示例。

For aligning images, stacking images, or positioning them in a grid, there are explained examples in the LaTeX Cookbook, Chapter 4, Working with Images.

让文本围绕图像流动

Letting text flow around images

虽然有点贪玩,你可能希望让文本围绕图形流动。我们可以使用wrapfig包及其wrapfigure环境来实现这一点。

Though it's a bit playful, you might wish to let the text flow around a figure. We can achieve this using the wrapfig package and its wrapfigure environments.

我们将修改之前嵌入图像的示例(参见图 5.3)。我们希望图像显示在左侧,并在右侧显示正文,并执行以下步骤:

We will modify our previous example that embedded an image (see Figure 5.3). We would like the image to appear on the left side, accompanied by the body text on the right side, with the help of the following steps:

  1. 在我们图 5.3的示例代码中,额外加载wrapfig包,如下所示:

    \documentclass[a5paper]{文章}

    \usepackage[english]{babel}

    \usepackage{盲文}

    \usepackage{graphicx}

    \usepackage{wrapfig}

    \pagestyle{空}

    \开始{文档}

  2. In our example code for Figure 5.3, additionally load the wrapfig package, as follows:

    \documentclass[a5paper]{article}

    \usepackage[english]{babel}

    \usepackage{blindtext}

    \usepackage{graphicx}

    \usepackage{wrapfig}

    \pagestyle{empty}

    \begin{document}

  3. 开始一个未编号的部分,并在一些填充文本中放置一个wrapfig环境,如下所示:

    \section*{围绕图像流动的文本}

    \盲文

    \begin{wrapfigure}{l}{4cm}

      \includegraphics[width=4cm]{ 示例图片}

      \caption{测试图}

    \结束{wrapfigure}

    \盲文

    \end{文档}

  4. Begin an unnumbered section, and place a wrapfig environment within some filler text, like this:

    \section*{Text flowing around an image}

    \blindtext

    \begin{wrapfigure}{l}{4cm}

      \includegraphics[width=4cm]{ example-image}

      \caption{Test figure}

    \end{wrapfigure}

    \blindtext

    \end{document}

  5. 编译文档看看。您应该看到以下输出:
  6. Compile the document and take a look. You should see the following output:
图 5.4 – 围绕图像流动的文本

图 5.4 – 围绕图像流动的文本

Figure 5.4 – Text flowing around an image

环绕图形环境具有与图形环境不同的参数。我们只使用了其中的两个。如果你需要更多,这里是完整的定义:

The wrapfigure environment has different parameters from the figure environment. We used just two of them. If you need more, here's the complete definition:

\begin{wrapfigure}[行数]{放置}[悬垂]{宽度}

\begin{wrapfigure}[number of lines]{placement}[overhang]{width}

第一个可选参数说明换行的文本行数。如果省略,这将根据高度自动计算。第二个参数placement可以是右、左、内或外侧的rlio字符之一,或者具有相同含义的相应大写字母RLIO ,但允许浮动的数字。只允许使用一个字符来指定选项。另一个可选参数overhang可以设置图形悬垂到页边距的宽度;默认为0角 最后一个也是强制性的参数给出了图形的宽度。

The first optional argument states the number of wrapped text lines. If omitted, this would be automatically calculated from the height. The second argument, placement, can be one of r, l, i, and o characters for the right, left, inner, or outer side, or the corresponding uppercase letters R, L, I, O with the same meaning, but allowing the figure to float. Only one character for specifying the option is allowed. The other optional argument, overhang, can set a width by which the figure should hang out into the margin; the default is 0 pt. The final—and mandatory—argument gives the width of the figure.

你可以阅读更多内容在https://texdoc.org/pkg/wrapfig的手册中。

You can read more in the manual at https://texdoc.org/pkg/wrapfig.

概括

Summary

在本章中,我们学习了如何在文档中包含图像。我们现在知道可以使用哪些文件类型以及如何在文档中放置图形。

In this chapter, we have learned how to include images in our document. We now know which file types we can use and how to place figures in our document.

LaTeX 可以生成类似于目录的图表列表。我们将在第 8 章列表内容和参考”中处理此类列表。

LaTeX can generate a list of figures like a table of contents. We will deal with such lists in Chapter 8, Listing Contents and References.

由于我们的数字已编号,因此我们可以使用这些数字在文本中引用它们。在第 7 章使用交叉引用中,我们将了解如何使用 LaTeX 的内置交叉引用功能来做到这一点。

As our figures are numbered, we can use these numbers to refer to them within the text. In Chapter 7, Using Cross-References, we will figure out how to do this, benefiting from LaTeX's built-in cross-referencing capabilities.

在下一章中,我们将使用表格,我们将看到表格定位与图形定位非常相似。

In the next chapter, we will work with tables, and we will see that table positioning is very similar to figure positioning.

第 6 章:创建表

Chapter 6: Creating Tables

科学文件和其他文件不仅包含纯文本;他们还在表格中提供信息和数据。我们将在本章中熟悉它。

Scientific documents and others do not just contain plain text; they also present information and data in tables. We shall become familiar with that in this chapter.

在本章中,我们将学习如何执行以下操作:

In this chapter, we will learn how to perform the following:

  • 使用制表位在列中书写
  • Using tab stops to write in columns
  • 排版表
  • Typesetting tables
  • 向表格添加标题
  • Adding captions to tables
  • 使用包进行进一步定制
  • Using packages for further customization

让我们来解决这些任务。我们将从简单地按列排列文本开始。

Let's tackle these tasks. We will start by simply arranging text in columns.

技术要求

Technical requirements

您需要安装 LaTeX,或者您可以在https://latexguide.org/chapter-06在线编译示例代码。

You need to have a LaTeX installation, or you can compile the example code online at https://latexguide.org/chapter-06.

GitHub 上也提供了代码: https: //github.com/PacktPublishing/LaTeX-Beginner-s-Guide-2nd-Edition-/tree/main/Chapter_06_-_Creating_Tables

The code is also available on GitHub: https://github.com/PacktPublishing/LaTeX-Beginner-s-Guide-2nd-Edition-/tree/main/Chapter_06_-_Creating_Tables.

在本章中,我们将使用以下 LaTeX 包:arraybooktabscaptionmultirow

In this chapter, we will use the following LaTeX packages: array, booktabs, caption, and multirow.

我们还将简要介绍这些包:colorcolortbldcolumnlongtableltablexltxtablemicrotyperagged2erccolrotatingsiunitxstabularsupertabulartabularxtabularyxcolorxtab

We will also briefly talk about these packages: color, colortbl, dcolumn, longtable, ltablex, ltxtable, microtype, ragged2e, rccol, rotating, siunitx, stabular, supertabular, tabularx, tabulary, xcolor, and xtab.

使用制表位在列中书写

Using tab stops to write in columns

记住打字机和早期文字处理软件的时代?当我们需要在列中排列一些文本时,我们可以使用制表位。LaTeX 提供了一种类似的方式来轻松对齐列中的文本,即制表环境。

Remember the time of the typewriter and early word processing software? When we needed to line up some text in columns, we could use tab stops. LaTeX provides a similar way to easily align text in columns, namely, the tabbing environment.

我们想快速概述一下 LaTeX。在以下步骤的帮助下,我们将在每一行上显示一个点,与单词和冒号对齐:

We want to present a quick overview of LaTeX. We shall present one point on each line, aligned at words and colons, with the help of the following steps:

  1. 开始一个新文档并打开一个标签环境:

    \文档类{文章}

    \开始{文档}

    \begin{制表符}

  2. Begin a new document and open a tabbing environment:

    \documentclass{article}

    \begin{document}

    \begin{tabbing}

  3. 编写文本,使用\=设置制表位,并以\\结束该行:

      \emph{信息:} \= 软件 \= : \= \LaTeX \\

  4. Write the text, set tab stops with \=, and end the line with \\:

      \emph{Info:} \= Software \= : \= \LaTeX \\

  5. 添加更多行,使用\>移动到下一个制表位,然后再次使用\\结束行:

      \> 作者 \> : \> Leslie Lamport \\

      \> 网站 \> : \> www.latex-project.org

  6. Add further lines, move to the next tab stop with \>, and again, end lines with \\:

      \> Author \> : \> Leslie Lamport \\

      \> Website \> : \> www.latex-project.org

  7. 关闭制表环境并结束文档:

    \end{制表符}

    \end{文档}

  8. Close the tabbing environment and end the document:

    \end{tabbing}

    \end{document}

  9. 单击排版按钮编译文档,并查看输出:
  10. Click the Typeset button to compile the document, and take a look at the output:
图 6.1 – 简单对齐的文本

图 6.1 – 简单对齐的文本

Figure 6.1 – Simply aligned text

我们使用的制表符环境开始一个新行。我们使用三个简单的标签进行标记:

The tabbing environment that we used begins a new line. We used three simple tags for markup:

  • \=设置制表位。我们可以在一行中放置多个制表位。我们通常在第一行这样做。
  • \= sets a tab stop. We could put several tab stops on a line. We usually do it in the first row.
  • \\结束一行。
  • \\ ends a row.
  • \>转到下一个制表位。
  • \> goes to the next tab stop.

除了第一行,我们还可以在另一行使用\=来调整之前设置的制表位。例如,如果我们已经在文本行中使用了两个\>标签来转到两个制表位,则\=标签将放置(新的或替换的)第三个制表位。

Aside from the first row, we can also use \= in another row to adjust a previously set tab stop. For example, if we already used two \> tags in a text line to go to two tab stops, a \= tag would put a (new or replaced) third tab stop.

https://latexguide.org/tabbing上,您可以看到几个使用这些标签的示例。

At https://latexguide.org/tabbing, you can see several examples using these tags.

使用tabbing,我们可以快速生成包含左对齐文本的列。如果行标签环境的结束页,它将在下一页继续。因此,制表符是使表格跨越分页符甚至跨越多个页面的一种非常基本的方法。

With tabbing, we can quickly produce columns containing left-aligned text. If the rows of the tabbing environment reached the end of a page, it would continue on the next page. So, tabbing is a very basic way to make tables crossing page breaks or even spanning over multiple pages.

但是,如果一列太长,超出了制表位怎么办?让我们看看如何解决这个问题。

But what if a column is too long, running over the tab stop? Let's see how to solve that.

第 2 章格式化文本和创建宏,我们了解了很多字体命令和声明。我们看到了一个包含这些命令和示例输出的表格。现在我们自己创建这样一张表,如下:

In Chapter 2, Formatting Text and Creating Macros, we got to know a lot of font commands and declarations. We saw a table containing those commands and example output. Now we shall create such a table ourselves, as follows:

  1. 开始一个新文档,就像我们前面示例的第 1 步中的文档一样,但也定义一个用于设置标题字体的命令:

    \文档类{文章}

    \newcommand{\head}[1]{\textbf{#1}}

    \开始{文档}

    \begin{制表符}

  2. Begin a new document, like the one in step 1 of our previous example, but also define a command for setting the header font:

    \documentclass{article}

    \newcommand{\head}[1]{\textbf{#1}}

    \begin{document}

    \begin{tabbing}

  3. 使用\=编写第一行的一组制表位,并使用\>移动到制表位。使用\动词|…| 命令来排版 LaTeX 命令:

      \= \head{命令} \= \head{声明} \= \head{示例}\\

      \> \verb|\textrm{...}| \> \动词|\rmfamily| \> \rmfamily 文本\\

      \> \verb|\textsf{...}| \> \动词|\sffamily| \> \sffamily 文本\\

      \> \verb|\texttt{...}| \> \动词|\ttfamily| \> \tt家庭文本

  4. Write the first row's set of tab stops with \=, and use \> to move to the tab stops. Use the \verb|…| command to typeset the LaTeX commands:

      \= \head{Command} \= \head{Declaration} \= \head{Example}\\

      \> \verb|\textrm{...}| \> \verb|\rmfamily| \> \rmfamily text\\

      \> \verb|\textsf{...}| \> \verb|\sffamily| \> \sffamily text\\

      \> \verb|\texttt{...}| \> \verb|\ttfamily| \> \ttfamily text

  5. 结尾标签环境文档:

    \end{制表符}

    \end{文档}

  6. End the tabbing environment and the document:

    \end{tabbing}

    \end{document}

  7. 单击Typeset编译文档,并检查输出:
    图 6.2 – 重叠对齐的文本

    图 6.2 – 重叠对齐的文本

  8. Click on Typeset to compile the document, and examine the output:

    Figure 6.2 – Overlapping aligned text

  9. 正如我们所见,制表位太窄了。我们会更正它。创建一个包含制表位的新标题行,但这一次,我们将以\kill结束该行以隐藏该行。使用填充文本指定制表位之间的宽度,例如列中最长的文本。用进一步的字体命令完成它。制表符代码现在如下所示:

    \begin{制表符}

      \= \verb|\textrm{...}| \= \head{声明} \=

         \head{例子}\kill

      \> \head{命令} \> \head{声明} \> \head{示例}\\

      \> \verb|\textrm{...}| \> \动词|\rmfamily| \> \rmfamily 文本\\

      \> \verb|\textsf{...}| \> \动词|\sffamily| \> \sffamily 文本\\

      \> \verb|\texttt{...}| \> \动词|\ttfamily| \> \tt家庭文本

    \end{制表符}

  10. As we can see, the tab stops are too narrow. We shall correct it. Create a new head row containing the tab stops, but this time, we will end the line with \kill to hide that line. Use filler text to specify the width between the tab stops, such as the longest text in the column. Complete it with further font commands. The tabbing code now looks like this:

    \begin{tabbing}

      \= \verb|\textrm{...}| \= \head{Declaration} \=

         \head{Example}\kill

      \> \head{Command} \> \head{Declaration} \> \head{Example}\\

      \> \verb|\textrm{...}| \> \verb|\rmfamily| \> \rmfamily text\\

      \> \verb|\textsf{...}| \> \verb|\sffamily| \> \sffamily text\\

      \> \verb|\texttt{...}| \> \verb|\ttfamily| \> \ttfamily text

    \end{tabbing}

  11. 再次编译得到最终结果:
  12. Compile again to get the final result:
图 6.3 – 更正对齐的文本

图 6.3 – 更正对齐的文本

Figure 6.3 – Corrected aligned text

我们注意到我们的制表位设置得太窄,我们构建了一个包含制表位的新第一行。它由代表每列最宽条目的单词组成。为了隐藏这个额外的行,我们在该行的末尾使用了\kill命令;\kill在一行的末尾导致该行没有输出。

After we noticed that our tab stops had been set too narrow, we constructed a new first row containing the tab stops. It consists of words representing the widest entries of each column. To hide this additional row, we used the \kill command right at the end of the line; \kill at the end of a line causes this line to have no output.

就像在这个例子中一样,\verb|code| 命令“按原样”排版代码而不解释其中的命令。而不是| , 我们可以选择任何字符作为分隔符。\verb不能用于包括\section\footnote在内的命令参数,也不能用于表头。

Like in this example, the \verb|code| command typesets code “as it is” without interpreting commands within. Instead of |, we can choose any character as the delimiter. \verb cannot be used in arguments of commands including \section and \footnote, and not in table heads.

对于更长的逐字文本,请使用具有相同名称的环境:verbatim

For longer, verbatim text, use the environment with the same name: verbatim.

还有更多有用的命令,特别是如果您经常使用选项卡式文本:

There are further useful commands, especially if you work a lot with tabbed texts:

  • \+在一行的末尾(在\\之前)将后续行的左边距向右移动一个制表位。使用它两次,\+\+,将它向右移动两个制表位,依此类推。
  • \+ at the end of a line (before \\) moves the left margin of the subsequent lines one tab stop to the right. Use it twice, \+\+, to move it two tab stops to the right, and so on.
  • \-在行尾将后续行的左边距向左移动一个制表位。此外,在这里,\-\-会将两个制表位向左移动。\-基本上是为了撤消之前\+所做的缩进。
  • \- at the end of a line moves the left margin of the subsequent lines one tab stop to the left. Also, here, \-\- would move two tab stops to the left. \- is basically for undoing a previous indentation made by \+.
  • \<取消该行前面的\+命令的效果。它将左边距向左移动一个制表位。我们应该只在一行的开头使用它。重复它以向左移动两个制表位。
  • \< cancels the effect of a preceding \+ command for that line. It moves the left margin one tab stop to the left. We should only use it at the beginning of a line. Repeat it to move two tab stops to the left.

提到的命令已经允许很好地使用tabbing环境。我们可以在参考手册中找到更多命令: https: //latex2e.org/tabbing

The mentioned commands already allow good use of the tabbing environment. We can find even more commands in the reference manual: https://latex2e.org/tabbing.

Tab 键环境中,声明是当前项目的本地声明。随后的\=\>\\\kill命令将停止效果。

Inside tabbing environments, declarations are local to the current item. A following \=, \>, \\, or \kill command would stop the effect.

此外,不能嵌套制表环境。

Also, tabbing environments cannot be nested.

那是一个方式轻松地在列中排列文本。现在让我们看看如何使用分隔线和对齐方式构建表格。

That was a way to arrange text in columns easily. Now let's see how to build tables with separation lines and alignment.

排版表

Typesetting tables

我们可能需要更复杂的结构和格式,例如列居中、分隔线,甚至嵌套结构。LaTeX 为排版简单和复杂的表格提供了表格环境。

We might need more complicated structures and formatting, such as centering in columns, dividing lines, or even nested structures. LaTeX provides the tabular environment for typesetting straightforward and complex tables.

我们现在将像前面的示例一样创建一个字体系列命令表,但这一次,我们希望使列中的所有条目彼此水平居中。我们还将按照以下步骤添加一些水平线来标记表格的边框和标题:

We will now create a table of font family commands as in the previous example, but this time, we would like to make all entries in a column horizontally centered to each other. We will also add some horizontal lines to mark the border and the header of the table by following these steps:

  1. 创建一个新文档。定义用于设置标题行字体的命令:

    \文档类{文章}

    \newcommand{\head}[1]{\textnormal{\textbf{#1}}}

    \开始{文档}

  2. Create a new document. Define a command for setting the font for the head row:

    \documentclass{article}

    \newcommand{\head}[1]{\textnormal{\textbf{#1}}}

    \begin{document}

  3. 开始表格环境。作为强制参数,提供ccc,代表三个居中的列:

    \开始{表格} {ccc}

  4. Begin a tabular environment. As a mandatory argument, provide ccc, standing for three centered columns:

    \begin{tabular}{ccc}

  5. 编写表头行,添加&以分隔列条目,并添加\\以结束行。使用\hline插入水平线:

      \h线

      \head{命令} & \head{声明} & \head{输出}\\

      \h线

  6. Write the table head row, add & to separate column entries, and add \\ to end rows. Use \hline to insert horizontal lines:

      \hline

      \head{Command} & \head{Declaration} & \head{Output}\\

      \hline

  7. 继续与表体和结束环境和文件。要排版 LaTeX 命令,请编写\verb|\command| :

      \动词|\textrm| & \动词|\rmfamily| & \rmfamily 示例文本\\

      \动词|\textsf| & \动词|\sffamily| & \sffamily 示例文本\\

      \动词|\texttt| & \动词|\ttfamily| & \ttfamily 示例文本\\

      \h线

    \结束{表格}

    \end{文档}

  8. Continue with the table body and end the environment and the document. To typeset LaTeX commands, write \verb|\command|:

      \verb|\textrm| & \verb|\rmfamily| & \rmfamily Example text\\

      \verb|\textsf| & \verb|\sffamily| & \sffamily Example text\\

      \verb|\texttt| & \verb|\ttfamily| & \ttfamily Example text\\

      \hline

    \end{tabular}

    \end{document}

  9. 单击文档上的排版以查看表格:
  10. Click on Typeset on the document to see the table:
图 6.4 – 一个简单的表格

图 6.4 – 一个简单的表格

Figure 6.4 – A simple table

步骤 2中,在强制参数中,我们写了一个字符列表。每个字符代表一个格式选项。因为我们使用了三个字符,所以我们得到了三列。c代表居中对齐。因此,所有列的条目都已居中。

In step 2, in the mandatory argument, we wrote a list of characters. Each character stands for a formatting option. As we used three characters, we've got three columns. c stands for centered alignment. Therefore, the entries of all columns have been centered.

步骤 34中,列条目用&分隔,而\\终止一行。不要以\\结束最后一行,除非您还想在下面写一行。在我们的源代码中对齐符号以保持其可读性也是一个好主意。

In steps 3 and 4, column entries are separated with &, while \\ terminates a row. Don't end the last line with \\ unless you further wish to write a line below. It's also a good idea to align the ampersands in our source code to keep it readable.

在列条目中,您可以使用普通文本和 LaTeX 命令。与在Tab 键环境中一样,声明对于卷曲单元格是局部的,就像花括号包围每个单元格的内容一样。

Inside the column entries, you may use ordinary text as well as LaTeX commands. As in the tabbing environment, declarations are local to the curly cell, like if curly braces surrounded each cell's content.

此外,tabular有一个可选的对齐参数,就像minipage一样。所以,完整的定义如下:

Furthermore, tabular has an optional alignment argument just like minipage. So, the complete definition is as follows:

\begin{tabular}[位置]{列说明符}

\begin{tabular}[position]{column specifiers}

  第 1 列第 1 行条目 & 第 1 列第 2 条目 ... & 第 1 列第 n 条目\\

  row 1 col 1 entry & row 1 col 2 entry ... & row 1 col n entry\\

  ...

  ...

\结束{表格}

\end{tabular}

在可选的[position]参数中,t表示在顶行对齐,b表示在底行对齐。默认为垂直居中对齐方式c。如果您想将两个表格彼此相邻放置或放在其他文本中,则此可选参数可能会派上用场。

In the optional [position] argument, t means alignment at the top row, and b means alignment at the bottom row. The default is vertically centered alignment, c. This optional argument may come in handy if you would like to place two tables next to each other or within other text.

我们将在以下部分学习如何自定义表格,例如添加行、左对齐、右对齐或居中对齐,以及跨多列或多行的单元格。

We will learn how to customize tables in the following sections, such as adding lines, aligning to left, right, or center, and spanning cells over multiple columns or rows.

在表格中画线

Drawing lines in tables

在tabular中,我们可以使用三种类型的线:

Within tabular, we can use three types of lines:

  • \hline在表格的整个宽度上绘制一条水平线。
  • \hline draws a horizontal line over the whole width of the table.
  • \cline{mn}绘制一条水平线,从m列开始,到n列结束。该语法是必需的;如果此行仅适用于一个特定的列,例如,仅适用于第 3 列,您仍应编写\cline{3-3}
  • \cline{m-n} draws a horizontal line starting at the beginning of column m and ending at the end of column n. That syntax is required; if this line is only for one particular column, for example, only column 3, you should still write \cline{3-3}.
  • \vline在当前行的整个高度和深度上绘制一条垂直线。
  • \vline draws a vertical line over the full height and depth of the current row.

我们将在以下部分中使用\hline 。

We will use \hline in the following sections.

理解格式化参数

Understanding formatting arguments

当然,进一步格式化是可能的。看看这个示例表,我们在其中添加lcrp作为参数:

Of course, further formatting is possible. Have a look at this example table, where we add l, c, r, and p as arguments:

\begin{tabular}{|l|c|r|p{1.7cm}|}

\begin{tabular}{|l|c|r|p{1.7cm}|}

  \h线

  \hline

  左&居中&右&一个完全对齐的段落单元格\\

  left & centered & right & a fully justified paragraph cell\\

  \h线

  \hline

  l & c & r & p\\

  l & c & r & p\\

  \h线

  \hline

\结束{表格}

\end{tabular}

此代码将生成下表:

This code would produce the following table:

图 6.5 – 具有不同对齐方式的表格

图 6.5 – 具有不同对齐方式的表格

Figure 6.5 – A table with different alignments

表格环境理解的选项如下:

The options understood by the tabular environment are as follows:

  • l左对齐。
  • l for left alignment.
  • c居中对齐。
  • c for centered alignment.
  • r右对齐。
  • r for right alignment.
  • p{width}用于特定宽度的“段落”单元格。如果您将多个p单元格并排放置,它们将在顶行对齐。它相当于在一个单元格中使用\parbox[t]{width}
  • p{width} for a “paragraph” cell of a certain width. If you place several p cells next to each other, they will be aligned at their top line. It's equivalent to using \parbox[t]{width} within a cell.
  • @{code}在列之前或之后插入代码而不是空白空间。代码也可以是一些文本,也可以保留为空以避免出现此空格,例如@{}
  • @{code} inserts code instead of empty space before or after a column. The code can also be some text, or it could be left empty to avoid this space, such as @{}.
  • | 代表一条垂直线。
  • | stands for a vertical line.
  • *{n}{options}相当于n 个options副本,其中n是一个正整数,options可能由一个或多个列说明符组成,也包括* 。

    提示

    强烈建议避免表格中的垂直线。线条应该巧妙地支持你的信息,但它们不应该让阅读变得困难。

  • *{n}{options} is equivalent to n copies of options, where n is a positive integer and options may consist of one or more column specifiers, including * as well.

    Tip

    It is strongly advised to avoid vertical lines in tables. Lines should subtly support your information, but they should not make reading difficult.

使用\usepackage{array}加载数组包后,您可以使用一些选项,例如:

After loading the array package with \usepackage{array}, you may use some options, such as the following:

  • m{width}类似于\parbox{width}:基线在中间。
  • m{width} is similar to \parbox{width}: the baseline is in the middle.
  • b{width}就像\parbox[b]{width}:基线在底部。
  • b{width} is like \parbox[b]{width}: the baseline is at the bottom.
  • !{code}可以像|一样使用 但插入代码而不是垂直线。与@{…}相反,列之间的空间不会被抑制。
  • !{code} can be used like | but inserts code instead of a vertical line. In contrast to @{…}, the space between columns will not be suppressed.
  • >{code}可以在lcrpmb选项之前使用,并在该列的每个条目的开头插入代码。
  • >{code} can be used before an l, c, r, p, m, or b option, and inserts code right at the beginning of each entry of that column.
  • <{code}可以在lcrpmb选项之后使用,并在该列条目的末尾插入代码。
  • <{code} can be used after an l, c, r, p, m, or b option, and inserts code at the end of the entry of that column.

此示例显示加载数组并使用@{}pmb对齐参数的效果:

This example shows loading array and using the effect of @{} and the p, m, and b alignment arguments:

\文档类{文章}

\documentclass{article}

\usepackage{数组}

\usepackage{array}

\开始{文档}

\begin{document}

\begin{tabular}{@{}lp{1.2cm}m{1.2cm}b{1.2cm}@{}}

\begin{tabular}{@{}lp{1.2cm}m{1.2cm}b{1.2cm}@{}}

  \h线

  \hline

  基线并在顶部对齐并在中间对齐

  baseline & aligned at the top & aligned at the middle

  & 在底部对齐\\

  & aligned at the bottom\\

  \h线

  \hline

\结束{表格}

\end{tabular}

\end{文档}

\end{document}

输出表格如下:

The output table is as follows:

图 6.6 – 具有不同垂直对齐方式的表格

图 6.6 – 具有不同垂直对齐方式的表格

Figure 6.6 – A table with different vertical alignments

查看图 6.6的最后一列——文本未与表格单元格的底部对齐,因为选项b表示单元格文本的基线应为底线。基线垂直对齐以处于同一水平。因此,要将基线作为其底线的文本与其他基线对齐,它必须向上移动。可以把基线看做锚线,所有锚点都在s我的高度。

Look at the last column of Figure 6.6 – the text is not aligned to the bottom of the table cell since option b means that the baseline of the cell text shall be the bottom line. Baselines are vertically aligned to be at the same level. So, to align text where the baseline is its bottom line with the other baselines, it has to move up. You can consider baselines as anchor lines, and all anchors are at the same height.

增加行高

Increasing the row height

您可以注意到水平线几乎触及单元格中的字母,尤其是大写字母。array包引入了一个称为\extrarowheight长度。如果它有一个正值,这将被添加到表格每一行的高度。

You may have noticed that horizontal lines nearly touch the letters in the cells, especially capital letters. The array package introduces a length called \extrarowheight. If it has a positive value, this will be added to the height of every row of the table.

下一个例子,在本章的第一个例子之后,展示了如何在突出显示的行中扩展行高。此外,它还显示了更多数组选项的效果,如如下:

The next example, following the very first example of this chapter, shows how to extend the row height in the highlighted line. Additionally, it shows the effect of further array options, as follows:

\文档类{文章}

\documentclass{article}

\usepackage{数组}

\usepackage{array}

\setlength{\extrarowheight}{4pt}

\setlength{\extrarowheight}{4pt}

\开始{文档}

\begin{document}

\begin{tabular}{@{}>{\itshape}ll!{:}l<{.}@{}}

\begin{tabular}{@{}>{\itshape}ll!{:}l<{.}@{}}

  \h线

  \hline

  信息: & 软件 & \LaTeX\\

  Info:     & Software & \LaTeX\\

  & 作者 & 莱斯利·兰波特\\

  & Author  & Leslie Lamport\\

  & 网站 & www.latex-project.org\\

  & Website & www.latex-project.org\\

  \h线

  \hline

\结束{表格}

\end{tabular}

\end{文档}

\end{document}

输出如下:

The output is as follows:

图 6.7 – 拉伸表

图 6.7 – 拉伸表

Figure 6.7 – A stretched table

在这里,我们使用>{\itshape}将一行的字体更改为斜体。>{}通常用于插入对齐声明,例如\centering尽管如此,还是有一个陷阱:这样的声明可能会改变\\的内部含义,它是表中\tabularnewline的快捷方式。但是array包提供了修复它的命令。在这种情况下,只需添加\arraybackslash,如以下示例所示:

Here, we used >{\itshape} to change the font of a row to italic. >{} is often used to insert an alignment declaration such as \centering. Still, there's a pitfall: such declarations might change the internal meaning of \\, which is a shortcut for \tabularnewline within tables. But the array package offers a command to repair it. In such cases, just add \arraybackslash, as in the following example:

\begin{tabular}{>{\centering\arraybackslash}p{5cm}}

\begin{tabular}{>{\centering\arraybackslash}p{5cm}}

否则,由pmb声明的段落单元格的内容将完全对齐。

Otherwise, the content of paragraph cells stated by p, m, or b will be fully justified.

在特定行之后,您可以使用可选参数\\添加垂直空间,例如\\[10pt]

After a specific row, you can add vertical space with the optional argument of \\, such as \\[10pt].

您甚至可以拉伸整个表格:\arraystretch命令包含一个默认值为1的拉伸因子。只是重新定义它。例如,\renewcommand{\arraystretch}{1.5}会将行高增加 50%。你可以在小组或环境中使用它以保持局部效果。

You may even stretch a whole table: the \arraystretch command contains a stretching factor with a default value of 1. Just redefine it. For example, \renewcommand{\arraystretch}{1.5} will increase the height of the rows by 50 percent. You could use it inside a group or an environment to keep the effect local.

美化餐桌

Beautifying tables

我们的桌子仍然不像好书上看起来那么完美。特别是,线条及其与文本的距离可能需要改进。booktabs包来拯救加载后,您可以使用替换\hline\cline的新行命令来提高表格的质量。

Our tables still don't look as perfect as they look in good books. Particularly, the lines and their distances to the text might need improvement. The booktabs package comes to the rescue. After loading it, you can enhance the quality of your tables with new line commands replacing \hline and \cline.

我们将在以下步骤的帮助下使用booktabs引入的新命令:

We shall use the new commands introduced by booktabs with the help of the following steps:

  1. 在我们之前的图 6.4示例中,加载booktabs包:

    \usepackage{书签}

  2. In our previous example for Figure 6.4, load the booktabs package:

    \usepackage{booktabs}

  3. 使用\toprule\midrule\bottomrule而不是\hline。将厚度指定为可选参数。表格变成如下:

    \开始{表格} {ccc}

      \toprule[1.5pt]

      \head{命令} & \head{声明} & \head{输出}\\

      \中规

      \动词|\textrm| & \动词|\rmfamily| & \rmfamily 示例文本\\

      \动词|\textsf| & \动词|\sffamily| & \sffamily 示例文本\\

      \动词|\texttt| & \动词|\ttfamily| & \ttfamily 示例文本\\

      \底部规则[1.5pt]

    \结束{表格}

  4. Use \toprule, \midrule, and \bottomrule instead of \hline. Specify the thickness as an optional argument. The table becomes the following:

    \begin{tabular}{ccc}

      \toprule[1.5pt]

      \head{Command} & \head{Declaration} & \head{Output}\\

      \midrule

      \verb|\textrm| & \verb|\rmfamily| & \rmfamily Example text\\

      \verb|\textsf| & \verb|\sffamily| & \sffamily Example text\\

      \verb|\texttt| & \verb|\ttfamily| & \ttfamily Example text\\

      \bottomrule[1.5pt]

    \end{tabular}

  5. 编译看看区别:
  6. Compile to see the difference:
图 6.8 – 拉伸表

图 6.8 – 拉伸表

Figure 6.8 – A stretched table

英国排字工将一条线称为一条规则。booktabs开发人员为新命令选择了这个术语。这些是他们的定义:

British typesetters call a line a rule. The booktabs developer chose this terminology for the new commands. These are their definitions:

  • \toprule[thickness]可用于在表格顶部绘制一条水平线。如果需要,可以指定厚度,例如1pt0.5mm
  • \toprule[thickness] may be used to draw a horizontal line at the top of the table. If desired, a thickness may be specified, such as 1pt or 0.5mm.
  • \midrule[thickness]在表格的行之间绘制一条水平分界线。
  • \midrule[thickness] draws a horizontal dividing line between rows of a table.
  • \bottomrule[thickness]绘制一条水平线来完成表格。
  • \bottomrule[thickness] draws a horizontal line to finish off a table.
  • \cmidrule[thickness](trim){m–n}从列m到列n绘制一条水平线。(修剪)是可选的,如厚度。可以是(l)(r)来修剪线的左端或右端。写(lr)以在两端修剪。甚至可以添加{width},例如在(l{10pt})中,并指定修剪宽度。
  • \cmidrule[thickness](trim){m–n} draws a horizontal line from column m to column n. (trim) is optional, like thickness. It could be (l) or (r) to trim the line at its left or right end. Write (lr) to trim at both ends. Even adding {width}, such as in (l{10pt}), is possible and specifies the trim width.

booktabs包没有定义垂直线或线无论如何都不建议他们。这同样适用于双重规则。不建议使用垂直线或双线。它们甚至被广泛认为是糟糕的排版风格。

The booktabs package does not define vertical rules or lines. They are not advised anyway. The same applies to double rules. Neither vertical nor double lines are recommended. They are even widely considered to be bad typographic styles.

考虑使用\toprule和其他不带可选参数的行命令——让我们看看如何操作。

Consider using \toprule and the other line commands without optional arguments – let's figure out how.

调整长度

Adjusting lengths

我们简要地在本章增加行高部分介绍了\setlength命令。不要用\toprule\midrule\cmidrule\bottomrule的可选参数指定线宽,而是始终忽略它。相反,在序言中使用\setlength为整个文档设置一次。

We briefly introduced the \setlength command in the Increasing the row height section of this chapter. Instead of specifying a line thickness with an optional argument to \toprule, \midrule, \cmidrule, or \bottomrule, always omit it. Instead, set it once for your whole document with \setlength in the preamble.

因此,例如,在\usepackage{booktabs}之后,您可以编写以下内容:

So, for example, after \usepackage{booktabs}, you can write the following:

\setlength{\heavyrulewidth}{1.5pt}

\setlength{\heavyrulewidth}{1.5pt}

现在只要不带参数地使用\toprule\bottomrule ,它们的厚度总是1.5pt 。

Now just use \toprule and \bottomrule without an argument, and they will always be 1.5pt thick.

这些是我们可以调整的booktabs包的长度:

These are the lengths for the booktabs package that we can adjust:

  • \heavyrulewidth顶线和底线的粗细。
  • \heavyrulewidth for the thickness of the top and bottom lines.
  • \lightrulewidth为中间线的粗细与\midrule
  • \lightrulewidth for the thickness of the middle lines with \midrule.
  • \cmidrulewidth为\cmidrule的厚度。
  • \cmidrulewidth for the thickness of \cmidrule.
  • \cmidrulekern用于\cmidrule中的修剪。
  • \cmidrulekern for the trimming in \cmidrule.
  • \abovetopsep是顶部规则上方的空间;默认值为0pt
  • \abovetopsep is the space above the top rule; the default is 0pt.
  • \belowbottomsep是底部规则下方的空间;默认值为0pt
  • \belowbottomsep is the space below the bottom rule; the default is 0pt.
  • \aboverulesep指定\midrule\cmidrule\bottomrule上方的空间。
  • \aboverulesep specifies the space above \midrule, \cmidrule, and \bottomrule.
  • \belowrulesep用于\midrule\cmidrule\toprule下方的空间。
  • \belowrulesep is for the space below \midrule, \cmidrule, and \toprule.

尝试改变线条的粗细。长度已经有了合理的值,但您可以更改它们。因此,序言中的调整将适用于文档中的所有表格。

Try to change the thickness of the lines. The lengths already have reasonable values, but you may change them. So, the adjustment in your preamble would apply to all tables in your document.

跨越多列的条目

Spanning entries over multiple columns

我们可以通过共同的标题将关于同一主题的列分组。在这种情况下,我们应该合并标题中的两个单元格。\multicolumn命令为我们做了这个。

We can group columns concerning the same subject by a common header. In such a case, we should merge two cells in the header. The \multicolumn command does this for us.

关于我们的示例表,命令和声明都是输入,而其余列包含输出。我们将在标题中强调如下:

Regarding our example table, commands and declarations are both inputs, whereas the remaining column contains output. We shall emphasize that in our header as follows:

  1. 在我们之前的示例中,插入另一个标题行。使用*{3}l获得三个左对齐的列。在前后添加@{}以删除列间空间。使用\multicolumn合并单元格。更改列格式参数和中间规则。此处突出显示更改:

    \begin{tabular}{@{}*{3}l@{}}

      \toprule[1.5pt]

      \多列{2}{c}{\head{输入}} &

      \多列{1}{c}{\head{输出}}\\

      \head{命令} & \head{声明} & \\

      \cmidrule(r){1-2}\cmidrule(l){3-3}

      \动词|\textrm| & \动词|\rmfamily| & \rmfamily 示例文本\\

      \动词|\textsf| & \动词|\sffamily| & \sffamily 示例文本\\

      \动词|\texttt| & \动词|\ttfamily| & \ttfamily 示例文本\\

      \底部规则[1.5pt]

    \结束{表格}

  2. In our previous example, insert another header row. Use *{3}l to get three left-aligned columns. Put @{} before and after to remove inter-column space. Use \multicolumn to merge cells. Alter the column formatting argument and the middle rule. The changes are highlighted here:

    \begin{tabular}{@{}*{3}l@{}}

      \toprule[1.5pt]

      \multicolumn{2}{c}{\head{Input}} &

      \multicolumn{1}{c}{\head{Output}}\\

      \head{Command} & \head{Declaration} & \\

      \cmidrule(r){1-2}\cmidrule(l){3-3}

      \verb|\textrm| & \verb|\rmfamily| & \rmfamily Example text\\

      \verb|\textsf| & \verb|\sffamily| & \sffamily Example text\\

      \verb|\texttt| & \verb|\ttfamily| & \ttfamily Example text\\

      \bottomrule[1.5pt]

    \end{tabular}

  3. 编译并查看输出:
  4. Compile and see the output:
图 6.9 – 包含合并单元格的表格

图 6.9 – 包含合并单元格的表格

Figure 6.9 – A table with merged cells

我们两次使用\multicolumn命令——一次合并两个单元格,令人惊讶的是,另一次只合并一个单元格。我们先看看它的定义:

We used the \multicolumn command twice – once to merge two cells, and surprisingly, another time just for one cell. Let's first look at its definition:

\multicolumn{列数}{格式选项}{输入文本}

\multicolumn{number of columns}{formatting options}{entry text}

要跨越的列数可以是正整数或只是1。将应用格式化选项,而不是此单元格的表格定义中指定的选项。

The number of columns to be spanned may be a positive integer or just 1. The formatting options will be applied instead of the options specified in the tabular definition for this cell.

我们在使用\multicolumn{1}{c}{…}时利用了这一点,覆盖了l选项带有c选项的列仅使该单元格居中。

We took advantage of this when we used \multicolumn{1}{c}{…}, overriding the l option of the column with a c option to get just this cell centered.

我们所做的另一个改变是关注\cmidrule。我们使用它而不是\midrule,连同修剪参数,来获得输入和输出列之间的间隙。

The other change we made concerns \cmidrule. We used it instead of \midrule, together with the trimming argument, to get a gap between the input and the output column.

按列插入代码

Inserting code column-wise

我们想添加到表中的更多字体命令。写作\verb|...| 在每个牢房里都是令人厌烦的。我们将利用array包的>{...}功能来为列定义一次条目的格式。

There are many more font commands that we would like to add to the table. Writing \verb|…| in each cell is tiresome. We shall exploit the >{…} feature of the array package to define the formatting of the entries once for the column.

我们将修改定义以将我们的输入列设置为打字机字体。同时,我们会在左边插入一列,代表我们的命令类型:

We will modify the table definition to set our input columns in the typewriter font. At the same time, we will insert a column on the left, standing for our command type:

  1. 通过定义一个\normal命令来扩展我们示例的序言。它应使用\multicolumn生成一个l单元格,无论列格式是什么:

    \文档类{文章}

    \usepackage{数组}

    \usepackage{书签}

    \newcommand{\head}[1]{\textnormal{\textbf{#1}}}

    \newcommand{\normal}[1]{\multicolumn{1}{l}{#1}}

    \开始{文档}

  2. Extend the preamble of our example by defining a \normal command. It shall use \multicolumn to produce an l cell, no matter what the column formatting is:

    \documentclass{article}

    \usepackage{array}

    \usepackage{booktabs}

    \newcommand{\head}[1]{\textnormal{\textbf{#1}}}

    \newcommand{\normal}[1]{\multicolumn{1}{l}{#1}}

    \begin{document}

  3. 由于\verb不能用于表头,我们将使用\ttfamily来获取打字机字体。我们添加\textbackslash这样我们就不会在单元格中重复长命令短语。使用*{2}>{...}插入两次。然后,将<{Example text}添加到最后一列以节省打字工作:

    \begin{tabular}{@{}l*{2}{>{\ttfamily\textbackslash }l}l%

      <{示例文本}@{}}

      \toprule[1.5pt]

      & \多列{2}{c}{\head{输入}} &

      \多列{1}{c}{\head{输出}}\\

  4. As \verb cannot be used in table headers, we shall use \ttfamily to get the typewriter font. We add \textbackslash so we won't repeat the long command phrase within the cells. Use *{2}>{…} to insert it twice. Then, add <{Example text} to the last column to save typing work:

    \begin{tabular}{@{}l*{2}{>{\ttfamily\textbackslash }l}l%

      <{Example text}@{}}

      \toprule[1.5pt]

      & \multicolumn{2}{c}{\head{Input}} &

      \multicolumn{1}{c}{\head{Output}}\\

  5. 我们将使用\normal命令来避免标题中的打字机格式:

      & \normal{\head{命令}} & \normal{\head{声明}}

      & \普通的{}\\

      \cmidrule(lr){2-3}\cmidrule(l){4-4}

  6. We'll use the \normal command to avoid the typewriter formatting in the header:

      & \normal{\head{Command}} & \normal{\head{Declaration}}

      & \normal{}\\

      \cmidrule(lr){2-3}\cmidrule(l){4-4}

  7. 现在我们可以继续列出字体命令名称:

      家庭 & textrm & rmfamily & \rmfamily\\

      & textsf & sffamily & \sffamily\\

      & texttt & ttfamily & \ttfamily\\

      \底部规则[1.5pt]

    \结束{表格}

    \end{文档}

  8. Now we may continue listing the font command names:

      Family & textrm & rmfamily & \rmfamily\\

      & textsf & sffamily & \sffamily\\

      & texttt & ttfamily & \ttfamily\\

      \bottomrule[1.5pt]

    \end{tabular}

    \end{document}

  9. 编译,看结果:
  10. Compile, and look at the result:
图 6.10 – 带有列格式化命令的表格

图 6.10 – 带有列格式化命令的表格

Figure 6.10 – A table with column formatting commands

使用>{\textbackslash\ttfamily}l定义了一个左对齐的行,其中每个条目前面都有一个反斜杠并切换为打字机字体。我们写了*{2}{...}来定义这种风格的两列。因为示例文本已根据我们的表定义插入<{...},所以我们只需将声明放入没有文本的最后一列。

Using >{\textbackslash\ttfamily}l defines a left-aligned row, where each entry is preceded by a backslash and is switched to typewriter font. We wrote *{2}{…} to define two columns of this style. Because the example text has been inserted according to our table definition with <{…}, we just had to put the declarations into the last column without the text.

跨越多行的条目

Spanning entries over multiple rows

我们已经知道如何将文本跨越多列。但是如果文本应该跨越几行怎么办?LaTeX 没有为此定义命令。但是,multirow包可以。现在让我们使用multirow包合并单元格。

We already know how to span text over several columns. But what if the text should cross over several rows? LaTeX doesn't define a command for this. However, the multirow package does. Let's now merge cells using the multirow package.

在我们补充字体表之前,我们希望将“Family”这个词垂直居中,也就是说,将这个单元格跨越三行。这是我们的做法:

Before we complement the font table, we want to center the word “Family” vertically, that is, span this cell over three rows. This is how we do it:

  1. 在我们之前的示例中,额外加载multirow包:

    \usepackage{多行}

  2. In our previous example, additionally load the multirow package:

    \usepackage{multirow}

  3. 将单词Family替换为\multirow{3}{*}{Family}

    \multirow{3}{*}{Family} & textrm & rmfamily & \rmfamily\\

  4. Replace the word Family with \multirow{3}{*}{Family}:

    \multirow{3}{*}{Family} & textrm & rmfamily & \rmfamily\\

  5. 编译以查看小变化:
  6. Compile to see the small change:
图 6.11 – 垂直合并的单元格

图 6.11 – 垂直合并的单元格

Figure 6.11 – Vertically merged cells

我们用了\multirow命令跨越三行。它的定义如下:

We used the \multirow command to span three rows. Its definition is as follows:

\multirow{行数}{宽度}{输入文字}

\multirow{number of rows}{width}{entry text}

该条目将跨越使用\multirow 的的行数。如果数字是负数,它将跨越上面的行。

The entry will span that number of rows from the row on which \multirow is used. If the number is negative, it will span the rows above.

您可以指定宽度或只写*作为自然宽度。如果您设置宽度,LaTeX 会相应地换行文本。

You can specify a width or just write * for the natural width. If you set a width, LaTeX would wrap the text accordingly.

multirow理解用于微调的更多可选参数。https://texdoc.org/pkg/multirow上的文档对此进行了描述。

multirow understands further optional arguments for fine-tuning. The documentation at https://texdoc.org/pkg/multirow describes this.

现在我们知道如何创建表格,让我们看看如何添加标题文本。

Now that we know how to create tables, let's see how to add caption text.

向表格添加标题

Adding captions to tables

尤其对于较长的文本,我们想在表格中添加标题和数字。为表格编号便于参考,而标题则添加信息并告诉读者表格的内容。LaTeX 具有实现这一目标的内置功能。

Especially with longer text, we would like to add captions and numbers to our tables. Numbering the tables allows easy referencing, whereas captions add information and tell the reader what the table is about. LaTeX has built-in features to achieve that.

现在是时候完成我们的表格了。我们将列出剩余的字体命令。我们将使用第一列来描述字体命令的类别:系列、粗细、形状等。然后,我们将添加另一列来显示组合字体命令的效果。

Now it's time to complete our table. We shall list the remaining font commands. We'll use the first column to describe the category of the font commands: family, weight, shape, and so on. Then, we will add another column to show the effect of combining font commands.

最后,我们将表格居中并提供一个数字和一个标题。为此,我们将在示例表周围放置一个环境,在其中使用\centering ,并在环境的末尾插入一个\caption命令。我们将添加更多字体命令,并在右侧添加另一列,包含更多示例。让我们打破它分为以下步骤:

To finish, we shall center the table and provide a number and a caption. To do that, we will put a table environment around our example table, use \centering inside it, and insert a \caption command at the end of the table environment. We will add more font commands and add another column at the right, containing more examples. Let's break it down into the following steps:

  1. 从文档的文章类开始,加载arraybooktabsmultirow包:

    \文档类{文章}

    \usepackage{数组}

    \usepackage{书签}

    \usepackage{多行}

  2. Start with the document's article class, and load the array, booktabs, and multirow packages:

    \documentclass{article}

    \usepackage{array}

    \usepackage{booktabs}

    \usepackage{multirow}

  3. 定义一个用于格式化标题单元格的宏和一个用于我们希望左对齐的普通单元格的宏:

    \newcommand{\head}[1]{\textnormal{\textbf{#1}}}

    \newcommand{\normal}[1]{\multicolumn{1}{l}{#1}}

  4. Define a macro for formatting the header cells and a macro for normal cells, which we want to be left-aligned:

    \newcommand{\head}[1]{\textnormal{\textbf{#1}}}

    \newcommand{\normal}[1]{\multicolumn{1}{l}{#1}}

  5. 开始文档:

    \开始{文档}

  6. Begin the document:

    \begin{document}

  7. 现在,我们将创建表格,将内容居中,并写下所有行:

    \begin{表格}

      \定心

      \begin{tabular}{@{}l*{2}{>{\textbackslash\ttfamily}l}%

        l<{示例文本}l@{}}

        \toprule[1.5pt]

        & \多列{2}{c}{\head{输入}}

        & \多列{2}{c}{\head{输出}}\\

        & \normal{\head{命令}}

        & \normal{\head{声明}}

        & \normal{\head{单用}} & \head{组合}\\

        \cmidrule(lr){2-3}\cmidrule(l){4-5}

        \multirow{3}{*}{Family} & textrm & rmfamily

        & \rmfamily & \\

        & textsf & sffamily & \sffamily& \\

        & texttt & ttfamily & \ttfamily& \\

        \cmidrule(lr){2-3}\cmidrule(lr){4-4}

        \multirow{2}{1.1cm}{Weight} & textbf & bfseries

        & \bf系列

        & \multirow{2}{1.8cm}{\sffamily\bfseries 粗体和

          无衬线字体}\\

        & textmd & mdseries & \mdseries & \\

        \cmidrule(lr){2-3}\cmidrule(lr){4-4}

        \multirow{4}{*}{Shape} & textit & itshape

        & \itshape & \\

        & textsl & slshape & \slshape &

        \multirow{2}{1.8cm}{\sffamily\slshape 倾斜和

          无衬线字体}\\

        & textsc & scshape & \scshape & \\

        & textup & upshape & \upshape & \\

        \cmidrule(lr){2-3}\cmidrule(lr){4-4}

        默认 & textnormal & normalfont & \normalfont & \\

        \底部规则[1.5pt]

      \结束{表格}

      \caption{\LaTeX\ 字体选择}

    \茶几}

  8. Now, we will create the table, center the content, and write up all the rows:

    \begin{table}

      \centering

      \begin{tabular}{@{}l*{2}{>{\textbackslash\ttfamily}l}%

        l<{Example text}l@{}}

        \toprule[1.5pt]

        & \multicolumn{2}{c}{\head{Input}}

        & \multicolumn{2}{c}{\head{Output}}\\

        & \normal{\head{Command}}

        & \normal{\head{Declaration}}

        & \normal{\head{Single use}} & \head{Combined}\\

        \cmidrule(lr){2-3}\cmidrule(l){4-5}

        \multirow{3}{*}{Family} & textrm & rmfamily

        & \rmfamily & \\

        & textsf & sffamily & \sffamily& \\

        & texttt & ttfamily & \ttfamily& \\

        \cmidrule(lr){2-3}\cmidrule(lr){4-4}

        \multirow{2}{1.1cm}{Weight} & textbf & bfseries

        & \bfseries

        & \multirow{2}{1.8cm}{\sffamily\bfseries Bold and

          sans-serif}\\

        & textmd & mdseries & \mdseries & \\

        \cmidrule(lr){2-3}\cmidrule(lr){4-4}

        \multirow{4}{*}{Shape} & textit & itshape

        & \itshape & \\

        & textsl & slshape & \slshape &

        \multirow{2}{1.8cm}{\sffamily\slshape Slanted and

          sans-serif}\\

        & textsc & scshape & \scshape & \\

        & textup & upshape & \upshape  & \\

        \cmidrule(lr){2-3}\cmidrule(lr){4-4}

        Default & textnormal & normalfont & \normalfont & \\

        \bottomrule[1.5pt]

      \end{tabular}

      \caption{\LaTeX\ font selection}

    \end{table}

  9. 结束文档:

    \end{文档}

  10. End the document:

    \end{document}

  11. 编译,和我们的桌子现在准备好了:
  12. Compile, and our table is now ready:
图 6.12 – 带有标题的表格

图 6.12 – 带有标题的表格

Figure 6.12 – A table with a caption

我们将tabular环境放在table环境中。它以这种方式与\caption命令一起使用:

We put the tabular environment in a table environment. It's used in this way together with the \caption command:

\begin{table}[放置选项]

\begin{table}[placement options]

  表体

  table body

  \caption{表格标题}

  \caption{table title}

\茶几}

\end{table}

table环境是一个浮动环境,就像我们在第 5 章中看到的figure环境,包括图像。与普通文本不同,它们可能出现在其他地方,而不是它们在源代码中的位置所定义的地方。可选的placement参数确定表格可能出现的位置。然而,LaTeX 会在文本中放置一个表格,以实现良好的分页,而不会在页面末尾留出太多空白。我们在上一章讨论图形放置时讨论了浮动环境,这里同样适用,具有相同的放置参数。与数字一样,\begin{table}[htbp!]是最灵活的选择。

The table environment is a floating environment, just like the figure environment that we saw in Chapter 5, Including Images. Unlike normal text, they might appear somewhere else other than what is defined by their position in the source code. The optional placement argument determines where the table might appear. However, LaTeX will position a table within the text to achieve good page breaks without too much empty space at the end of a page. We discussed floating environments in the previous chapter when we talked about the placement of graphics, and the same applies here, with the same placement arguments. Like with figures, \begin{table}[htbp!] is the most flexible choice.

\caption也理解可选参数。如果你写\caption[short text]{long text},那么短文本将出现在表格列表中,而长文本将出现在文档中身体。如果您需要很长的描述性字幕,这将很有用。

\caption understands an optional argument as well. If you write \caption[short text]{long text}, then the short text will appear in a list of tables and long text in the document body. That's useful if you need very long descriptive captions.

表格自动编号。我们将在以下两节中讨论定位和格式化。

Tables are automatically numbered. Let's talk about positioning and formatting in the following two sections.

在上面放置字幕

Placing captions above

在排版中,它是将标题放在表格上方而不是下方是很常见的。我们可以通过在表体前写上\caption来实现。然而,LaTeX 期望标题总是在下面,导致表格看起来很局促。标题和下表之间的空间太小。因此,您可能希望添加一些空间,例如,在顶部标题后直接输入\vspace{10pt} 。

In typesetting, it's very common to place captions above tables instead of below. We can achieve this by writing \caption before the table body. However, LaTeX expects the caption to always be below, resulting in a cramped look to the table. There'll be too little space between the caption and the following table. So, you might wish to add some space, for instance, by entering \vspace{10pt} directly after a top caption.

还记得booktabs包吗?如果您以\toprule开始表格,只需指定\abovetopskip长度,如以下示例所示:

Remember the booktabs package? If you begin tables with \toprule, just specify the \abovetopskip length, as in the following example:

\setlength{\a​​bovetopsep}{10pt}

\setlength{\abovetopsep}{10pt}

通过将此行放入您的序言中,将在标题下方和表格顶行上方添加10pt空间。

By putting this line into your preamble, 10pt space would be added below the caption and above the top line of the table.

自定义字幕

Customizing captions

默认情况下,字幕看起来像正常的正文;没有视觉差异。您是否希望对字体大小、标签的不同格式、一些边距或缩进或任何其他自定义设置进行轻微更改?字幕包是大多数需求的答案。

By default, captions look like normal body text; there's no visual difference. Would you like to have a slight change in font size, different formatting of the label, some margins or indentation, or any other customization? The caption package is the answer to most needs.

通过使用几个选项,您可以增强所有字幕的视觉外观。尝试以下操作:

By using a few options, you could enhance the visual appearance of all of your captions. Try the following:

\usepackage[font=small,labelfont=bf,margin=1cm]{标题}

\usepackage[font=small,labelfont=bf,margin=1cm]{caption}

这样,您的标题将比普通文本小,带有数字的标签将是粗体,并且不会像普通文本一样宽。该软件包提供了许多功能,包括文档范围的设置和微调。它有据可查。所以,看看它的文档。访问https://texdoc.org/pkg/caption或在命令行输入texdoc 标题。

This way, your captions will be smaller than normal text, the label with the number will be bold, and it will not be as wide as normal text. The package offers a lot of features, both for document-wide settings and fine-tuning. It's very well documented. So, have a look at its documentation. Either visit https://texdoc.org/pkg/caption or type texdoc caption at the command line.

有各种用于表格布局和外观的包。在下一节中,我们将了解此类包。

There are various packages for table layout and appearance. In the next section, we will get to know such packages.

使用包进行进一步的定制

Using packages for further customizations

排版时表,我们可能会遇到进一步的挑战。例如,我们可能需要调整列宽、表格内的分页符、颜色、旋转表格以及获得特定的对齐方式。在以下部分中,我们将查看用于此类目的的其他包。

When typesetting tables, we may encounter further challenges. For example, we may need column width adjustment, page breaks within a table, color, to rotate a table, and get a specific alignment. In the following sections, we will have a look at additional packages for such purposes.

您可以在https://latexguide.org/tables上找到以下每个部分的示例表和文档链接。

You can find example tables and links to the documentation at https://latexguide.org/tables for each of the following sections.

自动调整列以适应表格宽度

Auto-fitting columns to the table width

lcr具有其内容的宽度。对于p列,您指定宽度。这样,很难找出表格的实际宽度。指定表格宽度并让 LaTeX 决定列的宽度不是一个好主意吗?tabularx包允许这样做。使用它看起来如下:

l, c, and r columns have the width of their content. For p columns, you specify the width. This way, it's hard to find out the actual width of the table. Wouldn't it be a good idea to specify the table width and let LaTeX decide how wide the columns may be? The tabularx package allows that. Using it looks as follows:

\usepackage{tabularx}

\usepackage{tabularx}

...

...

\begin{tabularx}{width}{列说明符}

\begin{tabularx}{width}{column specifiers}

  ...

  ...

\end{tabularx}

\end{tabularx}

新的tabularx环境需要一个额外的参数:表格的宽度。它引入了一种新的列类型X。它的行为类似于p列,但X列使用所有可用空间。一个X列将占用所有可用空间。如果您使用多个X列,它们将平分空间。因此,例如,您可以编写以下内容:

The new tabularx environment requires an additional argument: the width of the table. It introduces a new column type, X. It behaves like p columns, but X columns use all available space. One X column would take all of the available space. If you use several X columns, they will share the space equally. So, you could write, for instance, the following:

\begin{tabularx}{0.6\textwidth}{lcX}

\begin{tabularx}{0.6\textwidth}{lcX}

这样,您将得到一个占据文本宽度 60% 的表格——左对齐和居中列与其内容一样宽,段落列尽可能宽,直到达到 60%。

This way, you would get a table occupying 60 percent of the text width – a left-aligned and a centered column as wide as their content, and a paragraph column as wide as possible until 60 percent is reached.

虽然它易于使用,但tabularx文档提供了更多示例,告知我们有关派生类型的信息,并提供如下建议:不要让\multicolumn条目跨越任何X列。阅读https://texdoc.org/pkg/tabularx上的文档或在命令行中键入texdoc tabularx 。

Though it's easy to use, the tabularx documentation gives further examples, informs us about the derived types, and gives advice such as this: don't let \multicolumn entries cross any X column. Read the documentation at https://texdoc.org/pkg/tabularx or by typing texdoc tabularx at the command line.

有两种类似的方法:

There are two similar approaches:

  • LaTeX 提供了带星号的表格环境:

    \begin{tabular*}{width}[位置]{列说明符}

    表格通过修改列间空间来调整宽度。已开发tabularx以更有用的方式满足此需求。

  • LaTeX provides a starred version of the tabular environment:

    \begin{tabular*}{width}[position]{column specifiers}

    The table adjusts to width by modifying the inter-column space. tabularx has been developed to satisfy this need in a more useful way.

  • 表格提供了另一种复杂的表格环境,采用总宽度。它根据列中最宽单元格的自然宽度对每个列宽进行加权。
  • The tabulary package provides another sophisticated tabular environment taking the total width. It weights each column width according to the natural width of the widest cell in the column.

tabularx包是将表格宽度调整为文本宽度绝佳选择。

The tabularx package is an excellent choice for adjusting the table width to the text width.

生成多页表

Generating multi-page tables

所有表格环境直到现在我们才知道不能跨越页面边界。Tab环境是一个例外,因为它的性质不同。

All the tabular environments that we've got to know until now cannot cross page boundaries. The tabbing environment is an exception due to its different nature.

由于表格可能包含大量数据,因此我们需要一个解决方案。有几个包:

As tables might contain a lot of data, we need a solution. There are several packages:

  • longtable提供了一个同名的环境,类似于tabular的多页版本。它提供了在发生分页符时设置表格标题、连续标题以及特殊页眉和页脚的命令。这可能是多页表最简单的方法,因此也是最流行的。包文档描述了所有你需要的。结合booktabs包,你会得到很好的结果。这是最常用的包。
  • longtable provides an environment with the same name that's like a multi-page version of tabular. It provides commands to set table captions, continued captions, and special headers and footers when a page break occurs. It's probably the easiest way for multi-page tables and therefore it's the most popular. The package documentation describes all you need. In combination with the booktabs package, you will get excellent results. This is the most commonly used package.
  • ltxtable提供了longtabletabularx的组合。
  • ltxtable provides a combination of longtable and tabularx.
  • ltablex是另一种结合longtabletabularx功能的方法。
  • ltablex is another approach to combine the features of longtable and tabularx.
  • supertabular提供内部使用的表格环境的另一个多页扩展,提供可选的表尾和表头,其中出现分页符。建议用于两列文档。
  • supertabular offers another multi-page extension of the internally used tabular environment, providing optional table tails and heads where page breaks occur. It's recommended for two-column documents.
  • xtab扩展了supertabular,并减少了它的一些弱点。
  • xtab extends supertabular, and reduces some of its weaknesses.
  • stabular实现了一种在表格中使用分页符的简单方法,无需大惊小怪。
  • stabular implements a simple way to use page breaks in tabular without much fuss.

接下来,让我们看看如何为我们的表格添加颜色。

Next, let's see how to add color to our tables.

着色表

Coloring tables

我们甚至没有彩色文本,因为这通常不是我们首先使用 LaTeX 所做的。但当然,我们可以用文本和表格来做到这一点。对于着色文本,使用color包,或者更好的是,使用xcolor扩展。要为表格着色,请使用colortbl包。我们可以使用以下方法组合所有这些:

We haven't even colored text yet, as this usually isn't what we do first with LaTeX. But of course, we can do this with text as well as with tables. For coloring text, use the color package or, better, use the xcolor extension. To color tables, use the colortbl package. We can combine all this by using the following:

\usepackage[表]{xcolor}

\usepackage[table]{xcolor}

该包允许以多种方式为列、行、单个条目和行着色。包裹文档可以告诉你更多。

The package allows coloring columns, rows, single entries, and lines in many ways. The package documentation can tell you more.

使用横向

Using landscape orientation

我们可以排版横向非常宽的桌子。rotating包提供了一个名为sidewaystable 的环境,您可以使用来代替table环境。

We can typeset very wide tables in landscape orientation. The rotating package offers an environment called sidewaystable that you could use instead of the table environment.

表格和标题都将旋转 +/-90 度并放置在单独的页面上。该软件包提供了更多与旋转相关的环境和命令。

Both the table and caption would be rotated +/-90 degrees and placed on a separate page. The package provides further rotation-related environments and commands.

在小数点对齐列

Aligning columns at the decimal point

当条目在十进制标记处对齐并且可能在指数处对齐时,包含数字的内容更具可读性。几个包支持这个:

Columns containing numbers are more readable when the entries are aligned at the decimal marker and perhaps at an exponent. Several packages support this:

  • siunitx主要用于根据科学惯例以一致的方式使用单位排版值。但是,它为这种数字的十进制对齐提供了表格列类型。
  • siunitx is primarily intended for typesetting values with units in a consistent way, according to scientific conventions. However, it provides a tabular column type for such decimal alignment of numbers.
  • dcolumn提供了一种用于在逗号、句点或其他单个字符处对齐的列类型。
  • dcolumn offers a column type for aligning at a comma, a period, or another single character.
  • rccol定义了一种列类型,其中数字是“右居中”的,也就是说,它们相对于其他条目居中但彼此齐平。这样,对应的数字就会沿着列对齐。
  • rccol defines a column type where numbers are “right-centered,” that is, they are centered concerning other entries but flushed right to each other. This way, corresponding digits are aligned along the column.

dcolumnrccol相比,siunitx包更新且非常强大。

In contrast to dcolumn and rccol, the siunitx package is newer and very powerful.

处理窄列

Handling narrow columns

文字非常窄列可能需要特别注意,因为如果空间很小,就很难调整。这里有一些建议:

Text in very narrow columns might require special attention because justification is difficult if there's little space. Here's some advice:

  • 看看正确的连字符。如有必要,请按照我们在第 2 章格式化文本和创建宏中所做的那样对其进行改进。TeX 不对行、框或表条目的第一个单词进行连字。因此,一个长单词可能会越过列边界。要启用断字,插入一个空词:直接在开头写\hspace{0pt} 。
  • Have a look at the correct hyphenation. If necessary, improve it as we did in Chapter 2, Formatting Text and Creating Macros. TeX doesn't hyphenate the first word of a line, a box, or a table entry. So, a long word may cross the column boundary. To enable hyphenation, insert an empty word: write \hspace{0pt} directly at the beginning.
  • 加载微类型以改进理由。它在窄列中显示出最佳效果。
  • Load microtype to improve justification. It shows the best effect in narrow columns.
  • p列等中的完整理由可能看起来很糟糕,因为差距很大。考虑对此类列使用>{\raggedright\arraybackslash} 。
  • Full justification in p columns and the like may look bad because of big gaps. Consider using >{\raggedright\arraybackslash} for such columns.
  • ragged2e包中,使用\RaggedRight命令可以做得更好并且不需要\arraybackslash
  • From the ragged2e package, using the \RaggedRight command can do even better and doesn't need \arraybackslash.

用那些避免单词之间出现大差距的建议。

Use those suggestions to avoid big gaps between words.

概括

Summary

在本章中,我们学习了如何创建表。具体来说,我们处理了将文本放入列中、向表格中添加标题、跨越列和行、使用包来自动调整列以及创建彩色、横向甚至多页表格。

In this chapter, we have learned how to create tables. Specifically, we dealt with putting text into columns, adding captions to tables, spanning columns and rows, using packages to auto-fit columns, and creating colored, landscape, and even multi-page tables.

我们可以通过在命令行运行texdoc packagename或访问https://texdoc.org/pkg/packagename来打开每个提到的包的文档。

We can open the documentation of every mentioned package by running texdoc packagename at the command line or by visiting https://texdoc.org/pkg/packagename.

LaTeX 可以像目录一样生成表格列表。我们将在第 8 章列表内容和参考”中处理此类列表。

LaTeX can generate a list of tables like a table of contents. We will deal with such lists in Chapter 8, Listing Contents and References.

与数字类似,LaTeX 会自动为我们的表格编号。我们可以使用这些数字来引用表格。第 7 章使用交叉引用,致力于引用,所以我们现在将转向它。

Similar to figures, LaTeX numbers our tables automatically. We can use these numbers to reference the tables. Chapter 7, Using Cross-References, is dedicated to referencing, so we will turn to it now.

第 7 章:使用交叉引用

Chapter 7: Using Cross-References

我们的文档包含许多编号的内容,例如页面、部分、列表项、图形和表格。我们还没有列出更多;例如,如果你想写数学文本,你可以使用数字方程、定理、定义等等。

Our documents contain many numbered things, such as pages, sections, list items, figures, and tables. There's even more that we have not listed yet; for instance, if you would like to write mathematical text, you may use number equations, theorems, definitions, and many more.

我们对事物进行编号不仅是为了计算它们,也是为了在我们文档的其他地方引用它们。例如,在本章中,如果我想指出第三个数字,我会说“见图 7.3”。LaTeX 会自动为您枚举数字。如果你插入另一个图形,LaTeX 会自动调整它后面所有图形的编号。但是引用会发生什么?好吧,LaTeX 可以处理我们所有的交叉引用,这就是本章的主题。

We number things not just to count them but also to refer to them in other places of our document. For instance, in this chapter, if I wanted to point you towards the third figure, I would say "see Figure 7.3". LaTeX automatically enumerates figures for you. If you insert another figure, LaTeX will automatically adjust the numbering of all figures after it. But what happens with the references? Well, LaTeX can take care of all of our cross-references, which is the subject of this chapter.

在本章中,我们将了解以下内容:

In this chapter, we shall learn about the following:

  • 设置标签和参考
  • Setting labels and references
  • 使用高级参考
  • Using advanced referencing
  • 引用其他文档中的标签
  • Referring to labels in other documents
  • 将引用变成超链接
  • Turning references into hyperlinks

让我们在以下部分弄清楚如何完成所有这些工作。

Let's figure out how to do all this in the following sections.

技术要求

Technical requirements

您可以使用本地 LaTeX 安装,也可以在https://latexguide.org/chapter-07在线编译示例代码。

You can use a local LaTeX installation, or you can compile the example code online at https://latexguide.org/chapter-07.

该代码也可在 GitHub 上找到: https: //github.com/PacktPublishing/LaTeX-Beginner-s-Guide-2nd-Edition-/tree/main/Chapter_07_-_Using_Cross-References

The code is also available on GitHub: https://github.com/PacktPublishing/LaTeX-Beginner-s-Guide-2nd-Edition-/tree/main/Chapter_07_-_Using_Cross-References.

在本章中,我们将使用cleveref包和varioref包。

In this chapter, we will use the cleveref package and the varioref package.

我们还将了解fancyrefhyperrefxr包。

We will also get to know the fancyref, hyperref, and xr packages.

设置标签和参考

Setting labels and references

有能力去提到某个点,我们必须用标签标记它。那个的名字标签将在之后为我们提供参考。

To be able to refer to a certain point, we have to mark it with a label. The name of that label will serve us afterward for referencing.

我们现在将排版一个列表根据https://latex.org上的一项调查,最常用的论文包之一。通过\label命令,我们将标记我们稍后可以使用\ref命令引用的项目,如下所示:

We will now typeset a list of the most used packages for papers, according to a survey on https://latex.org. Through the \label command, we will mark items that we can later refer to with the \ref command, as shown here:

  1. 新建一本书文档:

    \文档类{书籍}

    \开始{文档}

  2. Create a new book document:

    \documentclass{book}

    \begin{document}

  3. 开始一个章节和一个部分,并为该部分放置一个标签:

    \chapter{统计}

    \section{LaTeX.org 用户最常用的软件包}

    \label{sec:packages}

  4. Start a chapter and a section, and place a label for this section:

    \chapter{Statistics}

    \section{Most used packages by LaTeX.org users}

    \label{sec:packages}

  5. 继续一些文本,包括脚注:

    LaTeX.org 使用的前五个软件包

    members\footnote{根据 2021 年的调查

    LaTeX.org\label{fn:project}}:

  6. Continue with some text, including a footnote:

    The Top Five packages, used by LaTeX.org

    members\footnote{according to the 2021 survey on

    LaTeX.org\label{fn:project}}:

  7. 写一个枚举列表,并在一些项目上贴上标签以供参考:

    \开始{枚举}

      \item graphicx\label{项目:graphicx}

      \项目通天塔

      \item amsmath\label{item:amsmath}

      \项目几何

      \项目超参考

    \结束{枚举}

  8. Write an enumerated list and put a label on a few items for referring to them:

    \begin{enumerate}

      \item graphicx\label{item:graphicx}

      \item babel

      \item amsmath\label{item:amsmath}

      \item geometry

      \item hyperref

    \end{enumerate}

  9. 让我们再看一个带有标签的章节:

    \第{数学}

    \标签{数学}

  10. Let's have another chapter with a label:

    \chapter{Mathematics}

    \label{maths}

  11. 结束于一些文本,包括参考:

    \emph{amsmath},在位置 \ref{item:amsmath}

    在 ~\ref{sec:packages} 部分的顶部列表中

    page~\pageref{sec:packages},是必不可少的

    \LaTeX 中的高质量数学排版。

    \emph{graphicx},在位置 \ref{item:graphicx},

    用于包含图像。另见脚注

    \ref{fn:project} 页面~\pageref{fn:project}。

    \end{文档}

  12. Finish with some text, including references:

    \emph{amsmath}, on position \ref{item:amsmath}

    of the top list in section~\ref{sec:packages} on

    page~\pageref{sec:packages}, is indispensable to

    high-quality mathematical typesetting in \LaTeX.

    \emph{graphicx}, on position \ref{item:graphicx},

    is for including images. See also the footnote

    \ref{fn:project} on page~\pageref{fn:project}.

    \end{document}

  13. 单击排版并查看输出。第 1 页以标题和项目符号列表开头。
    图 7.1 – 第一章

    图 7.1 – 第一章

    第 1 页以脚注结尾:

    图 7.2 – 脚注

    图 7.2 – 脚注

    第 2 页为空,因为第 2 章开始于右侧页面,即第 3 页:

    图 7.3 – 未解析的引用

    图 7.3 – 未解析的引用

  14. Click on Typeset and have a look at the output. Page 1 starts with headings and a bullet list.

    Figure 7.1 – First chapter

    Page 1 ends with a footnote:

    Figure 7.2 – Footnote

    Page 2 is empty since Chapter 2 starts on a right-hand page, which is page 3:

    Figure 7.3 – Unresolved references

  15. 你看到问号了吗?参考文献仍然缺失。再次编译,比较差异:
  16. Do you see the question marks? The references are still missing. Compile again and compare the differences:
图 7.4 – 解析引用

图 7.4 – 解析引用

Figure 7.4 – Resolved references

我们创建了交叉引用只需三个命令:

We created cross-references with just three commands:

  • \label标记位置。
  • \label marks the position.
  • \ref打印我们引用的元素的编号。
  • \ref prints the number of the element we refer to.
  • \pageref打印该元素的页码。
  • \pageref prints the page number of that element.

每个命令都将元素的名称作为参数。我们可以选择任何名称。

Each command takes the name of the element as an argument. We can choose any name.

我们不得不编译两次,因为 LaTeX 需要运行一次来​​生成 LaTeX 可以在下一次编译器运行期间读取的引用。如果 LaTeX 无法解析引用,它会打印两个问号。

We had to compile twice because LaTeX needs one run to produce the references that LaTeX can read during the next compiler run. If LaTeX cannot resolve a reference, it prints two question marks instead.

让我们仔细看看如何创建锚标签以及如何引用它。

Let's have a closer look at creating an anchor label and how to refer to it.

分配标签

Assigning a label

\label { name}命令将当前位置分配给名称标签。准确地说,它执行以下操作:

The \label{name} command assigns the current position to the name label. Precisely, it does the following:

  • 如果\label命令出现在普通文本中,则将分配当前的节单位,例如章或节。
  • If the \label command appears in ordinary text, the current sectional unit would be assigned, such as the chapter or the section.
  • 如果\label命令放在编号环境中,则该环境将分配给标签。
  • If the \label command is placed within a numbered environment, that environment would be assigned to the label.

因此,我们不能在表环境中标记一个部分。为了避免由于可能不合适的定位而导致的任何问题,一个好的经验法则是将\label命令放在我们想要引用的位置之后。例如,将其直接放在相应的\chapter之后或\section之后。

So, we cannot label a section within a table environment. To avoid any problems because of possible unsuitable positioning, a good rule of thumb is to place the \label command right after the position that we would like to refer to. For instance, place it directly after the corresponding \chapter or after \section.

图形表格环境中,\caption负责编号。这就是为什么\label必须放在\caption之后,而不是之前。

In the figure or table environments, \caption is responsible for the numbering. That's why \label has to be placed after \caption, not before.

因此,典型的浮动环境如下所示:

Therefore, typical floating environments look like the following:

\begin{图}[htbp!]

\begin{figure}[htbp!]

\定心

\centering

\includegraphics{文件名}

\includegraphics{filename}

\caption{测试图}\label{图:名称}

\caption{Test figure}\label{fig:name}

\结束{图}

\end{figure}

或者,我们可以在表的情况下执行以下操作:

Or, we could do the following in the case of a table:

\begin{table}[htbp!]

\begin{table}[htbp!]

\定心

\centering

\caption{表格描述}\label{tab:name}

\caption{table descripion}\label{tab:name}

\开始{表格}

\begin{tabular}{cc}

……

\结束{表格}

\end{tabular}

\茶几}

\end{table}

标签名称可以由字母、数字或标点字符组成。此外,标签名称区分大小写。

A label name may consist of letters, digits, or punctuation characters. Also, label names are case-sensitive.

如果您编写较大的文档,则标签数量可能会变得非常多。想象一个处理字体和字体表的部分——我们如何区分它们的标签?我们可以在它们前面加上环境类型。用fig:name标记图形、用tab:name 标记表格、用sec:name 标记部分已经成为一种常见的做法,在其他情况下也采用类似的方法。

If you write larger documents, the number of labels could become very high. Imagine a section dealing with fonts and a font table – how do we distinguish their labels? We could prefix them with the type of environment. It has become common practice to label figures with fig:name, tables with tab:name, sections with sec:name, with similar approaches in other cases.

在以下部分中,我们将看到几种引用标签的方法。

In the following sections, we will see several ways to refer to labels.

引用标签

Referring to a label

一旦我们设置了标签并且给它一个名字,我们可以引用那个名字。为此,我们使用\ref{name}此命令打印属于name的号码。我们甚至可以在相应的\label命令出现在我们的代码中之前使用它。

Once we set a label and give it a name, we may refer to that name. For this, we use \ref{name}. This command prints the number that belongs to name. We can even use it before the corresponding \label command appears in our code.

尽管它很简单,但它很强大。每次我们编译文档时,LaTeX 都会检查标签并重新分配数字,以响应所有更改。如果 LaTeX 注意到标签已更改,它会通知您需要第二次编译器运行来更新相应的标签。如有疑问,请编译两次。

Even though it's that simple, it's powerful. Each time we compile a document, LaTeX checks the labels and reassigns the numbers, responding to all changes. If LaTeX notices that labels have been changed, it would inform you that a second compiler run is required to update the corresponding labels. If in doubt, compile twice.

引用一个页面

Referring to a page

\pageref { name}命令类似于\ref的工作方式,除了它打印相应的页码。

The \pageref{name} command works analogous to \ref, except that it prints the corresponding page number.

如果我们更改章节和页码,所有参考文献会保持正确吗?让我们来测试一下吧!在本章开头插入一个虚拟部分和一个分页符,此处突出显示:

Would all the references stay correct if we changed the section and page numbers? Let's put it to the test! Insert a dummy section and a page break at the beginning of our chapter, highlighted here:

\chapter{统计}

\chapter{Statistics}

\section{简介}

\section{Introduction}

\新一页

\newpage

\section{LaTeX.org 用户最常用的软件包}

\section{Most used packages by LaTeX.org users}

\label{sec:packages}

\label{sec:packages}

点击排版一次。LaTeX 会编译它,但会显示一条消息:

Click on Typeset once. LaTeX will compile it, but it will show a message:

LaTeX 警告:标签可能已更改。重新运行以获得正确的交叉引用。

LaTeX Warning: Label(s) may have changed. Rerun to get cross-references right.

那就是我们要做!第二次排版,现在所有的数字都已经正确调整到section 1.2page 2

That's what we shall do! Typeset a second time, and now all the numbers have been correctly adjusted to section 1.2 and page 2:

图 7.5 – 自动调整参考

图 7.5 – 自动调整参考

Figure 7.5 – Automatically adjusted references

使用引用,连同页码引用,您可以编写以下内容:

Using a reference, together with the page number reference, you may write the following:

请参见 ~\pageref{fig:name} 页上的图~\ref{fig:name}。

See figure~\ref{fig:name} on page~\pageref{fig:name}.

正如您知道如何定义命令,您可以使此类引用更容易:

As you know how to define a command, you could make such referencing easier:

\newcommand{\fullref}[1]{\ref{#1} 页面~\pageref{#1}}

\newcommand{\fullref}[1]{\ref{#1} on page~\pageref{#1}}

……

见图~\fullref{fig:name}。

See figure~\fullref{fig:name}.

这样,您将获得完整的参考,例如参见第 32 页的图 4.2。但是,如果参考文献(例如图形)出现在同一页上,则写出页码看起来有点奇怪。我们怎样才能避免这种情况?varioref包提供一种方法。在接下来的部分中,我们将重点介绍诸如此类的高级参考。

This way, you would get a complete reference such as See Figure 4.2 on page 32. However, if the reference, such as for a figure, appears on the same page, writing out the page number looks a bit odd. How can we avoid that? The varioref package provides a way. We will focus on advanced referencing such as this in the following sections.

使用高级参考

Using advanced referencing

LaTeX 有助于自动化所有各种参考。它不仅限于编号。LaTeX 甚至可以自动命名和措辞。我们将在这里深入探讨。

LaTeX helps with automating all kinds of references. It's not only limited to numbering. LaTeX can even automate naming and phrasing. We will dig deeper into that here.

生成智能页面引用

Producing intelligent page references

varioref包_提供一个命令来添加上一页下一页或页码到参考文献,具体取决于在上下文中。

The varioref package offers a command to add on the preceding page, on the following page, or the page number to a reference, depending on the context.

我们将使用varioref命令引入变量引用\vref\vpageref,以实现增强的参考文本:

We will use the varioref commands to introduce variable references, \vref, and \vpageref, to achieve enhanced reference texts:

  1. 从设置标签和参考部分打开我们当前的示例。将varioref包添加到您的序言中。使用nospace包选项,确保varioref不会在引用之前或之后插入额外的不需要的空间:

    \usepackage[无空间]{varioref}

  2. Open our current example from the Setting labels and references section. Add the varioref package to your preamble. Use the nospace package option, which ensures that varioref doesn't insert additional undesirable space before or after a reference:

    \usepackage[nospace]{varioref}

  3. 编辑我们示例代码中第二章的内容:

    \emph{amsmath},在位置 \vref{item:amsmath}

    在 ~\vref{sec:packages} 部分的顶部列表中,

    是高质量数学必不可少的

    在 \LaTeX 中排版。\emph{graphicx},在位置上

    \vref{item:graphicx},用于包含图像。

    另见脚注 \vref{fn:project},即

    \vpageref{fn:项目}。

  4. Edit the content of the second chapter in our example code:

    \emph{amsmath}, on position \vref{item:amsmath}

    of the top list in section~\vref{sec:packages},

    is indispensable to high-quality mathematical

    typesetting in \LaTeX. \emph{graphicx}, on position

    \vref{item:graphicx}, is for including images.

    See also the footnote \vref{fn:project}, that is,

    \vpageref{fn:project}.

  5. 编译两次,看结果:
  6. Compile twice and look at the result:
图 7.6 – 页面底部的图像

图 7.6 – 页面底部的图像

Figure 7.6 – An image at the bottom of the page

\vref命令已检查与引用部分的标签的距离。由于标签在对开页上(这里,在双面布局的前一页上),\vref在前一页上写了1.2 。

The \vref command checked the distance from the label of the referenced section. As the label is on the facing page (here, on the preceding page in a two-sided layout), \vref wrote 1.2 on the preceding page.

\vpageref指的是段落末尾的对开页。

\vpageref refers to the facing page at the end of the paragraph.

\vref{name}的作用如下:

\vref{name} acts in the following way:

  • 如果引用和\label{name}在同一页上,它的行为与\ref完全一样。不会打印页码。
  • If the reference and \label{name} are on the same page, it behaves exactly like \ref. The page number will not be printed.
  • 如果引用和相应的\label在两个连续的页面上,\vref打印引用的数字,并在前一页下一页对页上打印。如果文档是双面的,也就是说,如果\label和参考落在双页跨页上,它将选择后者。
  • If the reference and the corresponding \label are on two successive pages, \vref prints the referred number and additionally on the preceding page, on the following page, or on the facing page. It will choose the latter if the document is two-sided, that is, if \label and the reference fall onto a double-page spread.
  • 否则,它将同时打印\ref\pageref
  • Otherwise, it will print both \ref and \pageref.

\vpageref等同于\pageref但在页面引用方面表现得像\vref 。

\vpageref is equivalent to \pageref but behaves like \vref concerning the page reference.

可变参考开关措辞之间有一点变化。它可以表示下一页下一页前一页上一页本页当前页。在双页布局中,它在对开页上一页下一页之间切换。有了这样的变化,文本读起来更自然。您可以在图 7.6中看到这种交替的措辞。

varioref switches between phrasings to have a bit of variation. It can say following page or next page, preceding page or previous page, this page or current page. And in a double-page layout, it switches between facing page and preceding page or next page. With such variation, the text reads more naturally. You can see this alternating phrasing in Figure 7.6.

即使varioref定义了新命令,您仍然可以使用标准的\ref\pageref命令。

Even though varioref defines new commands, you may still use the standard \ref and \pageref commands.

微调页面引用

Fine-tuning page references

如果标签和参考彼此非常接近,它们可能会落在同一页上,但不一定。在这种情况下,我们通常知道标签是在引用之前还是之后。varioref允许为\vpageref指定一个可选参数,正如我们在这里看到的:

If the label and reference are very close to each other, they would probably fall on the same page, but not necessarily. In such cases, we usually know if the label comes before or after the reference. varioref allows specifying an optional argument to \vpageref, as we can see here:

参见图 \vpageref[上]{fig:name}

see the figure \vpageref[above]{fig:name}

这将打印以下内容:

This will print the following:

  • 见上图,如果图在同一页
  • see the figure above, if the figure is on the same page
  • 看前一页的图,如果图在前一页
  • see the figure on the page before, if the figure is on the preceding page

而使用以下代码,我们将得到不同的输出:

Whereas with the following code, we will have a different output:

见脚注 \vpageref[below]{fn:name}

see the footnote \vpageref[below]{fn:name}

这将打印以下内容:

This will print the following:

  • 请参阅下面的脚注,如果脚注在同一页上
  • see the footnote below, if the footnote is on the same page
  • 如果脚注在下一页,请参阅下页的脚注
  • see the footnote on the following page, if the footnote is on the next page

\vpageref理解两个可选参数。在第一个可选参数中,如果标签和参考落在同一页面上,我们可以声明一个短语,而在第二个可选参数中,我们可以为标签和参考落在不同页面上的情况给出一个短语。因此,我们甚至可以编写以下内容:

\vpageref understands two optional arguments. While in the first optional argument we can state a phrase if the label and reference fall on the same page, in the second optional argument, we can give a phrase for the case when the label and reference fall on different pages. So, we could even write the following:

参见 \vpageref[上图][图]{fig:name}

see the \vpageref[above figure][figure]{fig:name}

这将打印以下内容:

This would print the following:

  • 看上图,如果图在同一页
  • see the above figure, if the figure is on the same page
  • 看上一页的图,如果上一页有图的话
  • see the figure on the previous page, if the figure is on the preceding page

听起来很复杂?好吧,您的需求可能会随着时间的推移而增加,需要更复杂的功能,以便这些功能有一天会派上用场。

Sounds complicated? Well, your demands might increase over time, requiring more sophisticated features so that these features might come in handy someday.

参考页面范围

Referring to page ranges

varioref提供两个更多命令:

varioref offers two more commands:

  • \vpagerefrange[opt]{label1}{label2},其中label1label2表示一个范围(例如从fig:afig:c的数字序列)。如果两个标签落在同一页上,则结果与\vpageref相同。否则,输出将是一个范围,例如第 32-36 页。如果两个标签都落在当前页面上,将使用opt 。
  • \vpagerefrange[opt]{label1}{label2}, where label1 and label2 denote a range (such as a sequence of figures from fig:a to fig:c). If both labels fall on the same page, the result is the same as with \vpageref. Otherwise, the output will be a range, such as on pages 32-36. opt would be used if both labels fall on the current page.
  • \vrefrange[opt]{label1}{label2}类似于\vref:参见图\vrefrange{fig:a}{fig:c}可能结果参见第 36-37 页的图 4.2 至 4.4
  • \vrefrange[opt]{label1}{label2} is analogous to \vref: see figures \vrefrange{fig:a}{fig:c} may result in see figures 4.2 to 4.4 on pages 36-37.

访问https://latexguide.org/chapter-07查看示例。

Visit https://latexguide.org/chapter-07 to see examples.

您可以在包手册中找到有关自定义的更多信息。像往常一样,您可以在命令提示符下通过键入texdoc varioref或访问https://texdoc.org/pkg/varioref打开它。

You can find more information regarding customization in the package manual. As usual, you can open it at the command prompt by typing texdoc varioref or by visiting https://texdoc.org/pkg/varioref.

使用自动引用名称

Using automatic reference names

厌倦了一遍又一遍地写figure~\ref{fig:name}table~\ref{tab:name} ?不会吧如果 LaTeX 知道\ref{name}是什么类型并且会自动写入类型名称和编号,那该有多好?如果我们想在整个文档中缩写fig.~\ref{fig:name}怎么办?cleverev包简化了工作它会自动确定交叉引用的类型和使用它的上下文。

Tired of writing figure~\ref{fig:name} and table~\ref{tab:name} again and again? Wouldn't it be great if LaTeX knew what type is meant by \ref{name} and would automatically write the type name and number? What if we want to abbreviate, say, fig.~\ref{fig:name} in the whole document? The cleverev package eases the work. It automatically determines the type of cross-reference and the context in which it is used.

您可以使用\cref\Cref而不是\ref;如果您想大写,请选择后者。相应的范围命令是\crefrange\Crefrange

You could use \cref or \Cref instead of \ref; choose the latter if you wish to capitalize. The corresponding range commands are \crefrange and \Crefrange.

我们将重写我们的第一个示例以使用cleveref进行引用。为了验证包是否运行良好,我们有意省略了\label\cref的标签名称中的前缀,如下所示:

We shall rewrite our first example to refer using cleveref. To verify that the package acts well, we intentionally omit prefixes in the label names for \label and \cref, as shown here:

  1. 按以下方式修改本章的第一个示例。修改后的行突出显示:

    \文档类{书籍}

    \usepackage{cleveref}

    \crefname{enumi}{position}{positions}

    \开始{文档}

    \chapter{统计}

    \标签{统计}

    \section{LaTeX.org 用户最常用的软件包}

    \标签{包}

    LaTeX.org 使用的前五个软件包

    members\footnote{根据 2021 年的调查

    LaTeX.org\label{项目}}:

    \开始{枚举}

      \item graphicx\label{图形x}

      \项目通天塔

      \item amsmath\label{amsmath}

      \项目几何

      \项目超参考

    \结束{枚举}

    \第{数学}

    \标签{数学}

    \emph{amsmath},在 \cref{amsmath} 中的顶级列表中

    \cref{packages} 的 \cref{stats},是必不可少的

    \LaTeX 中的高质量数学排版。

    \emph{graphicx},在 \cref{graphicx} 上,是为了

    包括图像。

    另见 \cpageref{project} 上的 \cref{project}。

    \end{文档}

  2. Modify our first example of this chapter in the following way. The modified lines are highlighted:

    \documentclass{book}

    \usepackage{cleveref}

    \crefname{enumi}{position}{positions}

    \begin{document}

    \chapter{Statistics}

    \label{stats}

    \section{Most used packages by LaTeX.org users}

    \label{packages}

    The Top Five packages, used by LaTeX.org

    members\footnote{according to the 2021 survey on

    LaTeX.org\label{project}}:

    \begin{enumerate}

      \item graphicx\label{graphicx}

      \item babel

      \item amsmath\label{amsmath}

      \item geometry

      \item hyperref

    \end{enumerate}

    \chapter{Mathematics}

    \label{maths}

    \emph{amsmath}, on \cref{amsmath} of the top list in

    \cref{packages} of \cref{stats}, is indispensable to

    high-quality mathematical typesetting in \LaTeX.

    \emph{graphicx}, on \cref{graphicx}, is for

    including images.

    See also the \cref{project} on \cpageref{project}.

    \end{document}

  3. 单击排版两次,然后检查引用是否具有正确的名称:
  4. Click on Typeset twice, and check that references have the correct names:
图 7.7 – 自动引用

图 7.7 – 自动引用

Figure 7.7 – Automated references

如我们所见,我们不需要指定我们引用的是哪个对象。\cref总是为我们选择正确的名字和正确的数字。这真的很有用。

As we can see, we didn't need to specify which object we refer to. \cref always chooses the right name and the correct number for us. That's really useful.

我们使用\crefname命令告诉cleveref它应该为枚举项使用哪个名称。\crefname的定义如下:

We used the \crefname command to tell cleveref which name it should use for enumerated items. The definition of \crefname is as follows:

\crefname{类型}{单数}{复数}

\crefname{type}{singular}{plural}

type可以是chaptersectionfiguretableenumiequationtheorem或我们尚未遇到的许多其他类型之一。cleveref对单个引用使用单数版本,对多个引用使用复数版本。如果您需要大写版本,请使用\Crefname。因此,典型的用法可能如下:

type may be one of chapter, section, figure, table, enumi, equation, theorem, or many other types we have not encountered yet. cleveref uses the singular version for single references and the plural version for multiple. If you need capitalized versions, use \Crefname. So, a typical use may be the following:

\crefname{figure}{fig.}{figs.}

\crefname{figure}{fig.}{figs.}

\Crefname{figure}{Fig.}{Figs.}

\Crefname{figure}{Fig.}{Figs.}

此外,在这里,我们可以使用这些命令来引用范围:

Also, here, we can refer to ranges using these commands:

  • \crefrange{label1}{label2}引用一系列参考
  • \crefrange{label1}{label2} to refer to a range of references
  • \cpagerefrange{label1}{label2}引用页面范围
  • \cpagerefrange{label1}{label2} to refer to a page range

举个例子会更清楚。让我们将此行添加到我们当前的示例中:

It will get clearer with an example. Let's add this line to our current example:

参见 \crefrange{graphicx}{amsmath} 和 \cpagerefrange{stats}{maths}。

See \crefrange{graphicx}{amsmath} and \cpagerefrange{stats}{maths}.

这给了我们:参见位置 1 到 3 和第 1 到 3 页

This gives us: See positions 1 to 3 and pages 1 to 3.

我们可以将好处总结如下:

We can sum up the benefits as follows:

  • 我们节省了很多打字。
  • We save a lot of typing.
  • 我们可以使用任意标签。fancyref包做类似的工作,但依赖诸如chapfigtab之类的前缀。
  • We could use arbitrary labels. The fancyref package does a similar job but relies on prefixes such as chap, fig, and tab.
  • 如果我们决定改变措辞,可以通过在序言中这样做一次来快速完成,在整个文件中产生预期的效果。
  • If we decide to change wordings, it could be done quickly by doing this once in the preamble, having the desired effect in the whole document.

但是,建议使用fig:sec:之类的前缀来区分引用对象的种类。这样,您的代码将变得更容易理解——这就是为什么它是常见的做法。

However, it's recommended to use a prefix such as fig: or sec: to distinguish the kind of referenced object. This way, your code would become more understandable – that's why it's common practice.

将智能引用与自动命名相结合

Combining intelligent references with automatic naming

作为cleveref完全支持varioref,你可以同时使用两者以充分利用它们。cleveref重新定义了varioref的命令以在内部使用\cref因此,您可以将varioref的良好页面引用功能与巧妙的命名自动化结合使用。

As cleveref fully supports varioref, you may use both to get the most out of them. cleveref redefines the commands of varioref to use \cref internally. So, you could use the good page referencing features of varioref together with the clever naming automation.

只需在cleveref之前加载varioref,如下所示:

Just load varioref before cleveref, as shown here:

\usepackage{varioref}

\usepackage{varioref}

\usepackage{cleveref}

\usepackage{cleveref}

现在,您可以使用\vref\cref\ref或其他命令——以合适的为准。

Now, you may use \vref, \cref, \ref, or the other commands – whichever seems appropriate.

虽然varioref有助于在文档中引用,但我们也可以在其他文档中使用对页面、部分等的引用。让我们仔细看看这个。

While varioref is helpful for referencing within a document, we can also use references to pages, sections, and so on in other documents. Let's take a closer look at this.

引用其他文档中的标签

Referring to labels in other documents

如果你写几个相关的相互引用的文档,您可能希望使用对另​​一个文档标签的引用。名为xr(代表外部引用)的包实现了这一点。首先,加载xr包:

If you write several related documents that refer to each other, you might want to use references to labels of another document. The package with the name xr (standing for external references) implements this. First, load the xr package:

\使用包{xr}

\usepackage{xr}

如果您需要引用外部文档中的部分或环境,例如doc.tex,请将此命令插入序言中:

If you need to refer to sections or environments in an external document, say, doc.tex, insert this command into your preamble:

\外部文档{文档}

\externaldocument{doc}

这使您能够另外引用在doc.tex中被赋予标签的任何内容。您可以对多个文档执行此操作。如果您需要在外部文档使用与主文档相同的\label时避免冲突,请使用\externaldocument的可选参数声明前缀,您可以使用它来添加前缀。例如,我们可以使用D-作为前缀:

This enables you to additionally refer to anything that has been given a label in doc.tex. You may do this for several documents. If you need to avoid conflicts when an external document uses the same \label as the main document, declare a prefix using the optional argument of \externaldocument, which you can use to add a prefix. For example, we can use D- as a prefix:

\externaldocument[D-]{文档}

\externaldocument[D-]{doc}

这样一来,所有来自doc.tex的引用将以D-为前缀,您可以编写\ref{D-name}来引用doc.tex中的名称。代替D-,您可以选择任何前缀来转换您的标签,使它们变得独一无二。

This way, all references from doc.tex would be prefixed by D-, and you could write \ref{D-name} to refer to name in doc.tex. Instead of D-, you may choose any prefix that transforms your labels such that they become unique.

在下一节中,我们将看到如何使引用处于活动状态,即可点击,这样点击就会将读者引导至带标签的对象。

In the next section, we will see how we can make references active, meaning clickable, so that a click will lead the reader to the labeled object.

将引用变成超链接

Turning references into hyperlinks

PDF文件提供书签和超链接功能。如何关于探索那个?有一个出色的包提供超链接支持——hyperref

PDF documents offer bookmarks and hyperlink capabilities. How about exploring that? There's an outstanding package that offers hyperlink support – the hyperref package.

通过在cleveref之前加载hyperref来尝试。此顺序对于引用的工作至关重要,因为cleveref会检测是否已加载hyperref并使引用指向超链接。即使没有任何选项或命令,您的文档也将尽可能地被超链接,原因如下:

Try it by loading hyperref right before cleveref. This order is essential for the references to work because cleveref detects whether hyperref has been loaded and makes the references to hyperlinks. Even without any options or commands, your document will be hyperlinked as much as possible because of the following:

  • 所有引用都变成超链接。单击这些数字中的任何一个以跳转到引用的表格、列表项、部分或页面。
  • All references become hyperlinks. Click on any of those numbers to jump to the referred table, list item, section, or page.
  • 每个脚注标记都是指向脚注文本的超链接。点击它跳转到那里。
  • Each footnote marker is a hyperlink to the footnote text. Click it to jump there.
  • 如果插入\tableofcontents ,您将获得PDF阅读器导航栏中列出的文档、章节和部分的书签列表。
  • If you insert \tableofcontents, you will get a bookmark list for the documents, chapters, and sections listed in a navigation bar of your PDF reader.

hyperref可以为您做更多的事情——将索引条目链接到文本段落、书目条目的反向引用等等。您可以使用选项(例如,为超链接选择颜色或框架)精细地自定义行为。因此,您应该牢记这个有价值的包裹。在第 12 章进一步增强您的文档,我们将回到这个主题。

hyperref can do even more for you – linking index entries to text passages, back-referencing of bibliography entries, and more. You can finely customize the behavior using options such as, for instance, choosing the color or frames for hyperlinks. So, you should keep that valuable package in mind. In Chapter 12, Enhancing Your Documents Further, we shall return to this topic.

一方面,hyperref检测许多其他包,例如varioref,并且可以将它们的命令转换为超链接;这就是为什么我们应该在大多数其他包之后加载hyperref。另一方面,一些特殊的包,例如cleveref,检测hyperref函数并在它们之上构建——在这种情况下,我们应该在hyperref之后加载它们。所以,如果你组合variorefcleverefhyperref,包加载顺序应如下:

On the one hand, hyperref detects many other packages, such as varioref, and can turn their commands into hyperlinks; that's why we should load hyperref after most other packages. On the other hand, some exceptional packages, such as cleveref, detect hyperref functions and build on them – in such cases, we should load them after hyperref. So, if you combine varioref, cleveref, and hyperref, the package loading order should be as follows:

\usepackage[无空间]{varioref}

\usepackage[nospace]{varioref}

\usepackage{hyperref}

\usepackage{hyperref}

\usepackage{cleveref}

\usepackage{cleveref}

hyperref包_手册有一整节是关于与其他包的兼容性和所需的加载顺序。通过在命令提示符下输入texdoc hyperref或访问https://texdoc.org/pkg/hyperref打开它。大多数时候,hyperref应该最后加载,除了手册中提到的一些例外。

The hyperref package manual has a whole section about compatibility with other packages and the required loading order. Open it by entering texdoc hyperref at the command prompt or visit https://texdoc.org/pkg/hyperref. Most of the time, hyperref should be loaded last, with a few exceptions mentioned in the manual.

概括

Summary

在本章中,我们学习了如何通过编号或相应页码来引用章节、节、脚注和环境。

In this chapter, we learned how to reference chapters, sections, footnotes, and environments by their number or by the number of the corresponding page.

使用标签进行引用,我们不需要自己指定一个数字;LaTeX 为我们确定页面、章节、脚注或环境的正确编号。

Using labels for referencing, we did not need to specify a number by ourselves; LaTeX determines the correct number of a page for us, or of a section, a footnote, or an environment.

我们甚至了解了一些巧妙的上下文相关引用方式。

We even got to know some clever ways of context-dependent referencing.

在下一章中,我们将处理列表,它主要由参考文献组成:目录、图表列表和参考书目。

In the next chapter, we shall deal with lists, which consist mainly of references: tables of contents, lists of figures and tables, and bibliographies.

第 8 章:列出内容和参考文献

Chapter 8: Listing Contents and References

LaTeX 使得创建用于多种用途的列表变得非常容易。例如,我们已经看到仅使用简单的\tableofcontents命令就可以创建一个漂亮的目录。它从标题和它们所在的页码中获取条目,并生成一个漂亮的列表。

LaTeX makes it very easy to create lists for many purposes. For example, we've seen that just the simple \tableofcontents command creates a nice-looking table of contents. It takes the entries from the headings and the numbers of the pages they fall on and produces a nice list.

目录( TOC )索引对于在书中导航很方便。表格清单和图表清单同样有用。通常,一篇学术论文或一本书需要一个引用列表,一个参考书目。完成本章后,您将了解如何创建此类列表以及如何自定义它们。

A table of contents (TOC) and an index are handy for navigating within a book. Lists of tables and lists of figures are similarly helpful. Usually, an academic paper or a book requires a list of references for citations, a bibliography. Once you finish this chapter, you will know how to create such lists and how to customize them.

在本章中,我们将讨论以下主题:

In this chapter, we will cover the following topics:

  • 自定义目录
  • Customizing the table of contents
  • 生成索引
  • Generating an index
  • 创建参考书目
  • Creating a bibliography
  • 更改标题
  • Changing the headings

我们将从内容开始。

We will start with the contents.

技术要求

Technical requirements

您可以使用本地 LaTeX 安装,也可以在https://latexguide.org/chapter-08在线编译示例代码。

You can use a local LaTeX installation, or you can compile the example code online at https://latexguide.org/chapter-08.

GitHub 上的代码位于https://github.com/PacktPublishing/LaTeX-Beginner-s-Guide-2nd-Edition-/tree/main/Chapter_08_-_Listing_Contents_and_References

The code is available on GitHub at https://github.com/PacktPublishing/LaTeX-Beginner-s-Guide-2nd-Edition-/tree/main/Chapter_08_-_Listing_Contents_and_References.

在本章中,我们将使用 LaTeX 标准功能和索引包。

In this chapter, we will use LaTeX standard features and the index package.

此外,我们将简要介绍以下包:biblatexcitehyperrefmakeidxminitocmultitocnatbibtitlesectitletoctocbibindtoclofturl

Furthermore, we will briefly talk about the following packages: biblatex, cite, hyperref, makeidx, minitoc, multitoc, natbib, titlesec, titletoc, tocbibind, tocloft, and url.

您可以在LaTeX Cookbook 的7 章目录、索引和参考书目中找到相关示例,本书网站上提供了代码示例: https: //latex-cookbook.net/chapter-7

You can find related examples in the LaTeX Cookbook, Chapter 7, Contents, Indexes, and Bibliographies, with code examples available on the book's website: https://latex-cookbook.net/chapter-7.

自定义目录

Customizing the table of contents

除了只需调用\tableofcontents即可获得预先设计的内容列表,LaTeX 提供了修改它的基本方法。让我们使用一些。

Besides just calling \tableofcontents to get a pre-designed list of contents, LaTeX provides basic ways to modify it. Let's use some.

我们将创建一个我们将用于自定义的文档,它也将是我们以下部分的工作示例。

We will create a document that we will use for customizing, and it will also be our working example for the following sections.

我们将构建包含一些标题的文档框架。我们将修改自动创建的目录,使其更加细致并包含更多条目。

We will build the frame of a document containing some headings. We will modify the automatically created table of contents to be more nuanced and to contain additional entries.

第 3 章设计页面中,我们看到了\tableofcontents的效果。LaTeX 从标题中收集条目。我们将使用小节级别的标题。

In Chapter 3, Designing Pages, we saw the effect of \tableofcontents. LaTeX collected the entries from the headings. We will use headings down to the subsubsection level.

稍后,我们将进一步扩展 TOC。我们将手动为某些标题添加条目。让我们从基本文档开始:

Later, we will extend the TOC further. We will manually add entries for some headings. Let's start with the base document:

  1. 开始新书文档

    \文档类{书籍}

  2. Start a new book document:

    \documentclass{book}

  3. 将目录的深度值设置为3以包含向下到小节级别的标题:

    \setcounter{tocdepth}{3}

  4. Set the table of contents' depth value to 3 to include headings down to the subsubsection level:

    \setcounter{tocdepth}{3}

  5. 开始文档:

    \开始{文档}

  6. Begin the document:

    \begin{document}

  7. 在开头打印目录:

    \目录

  8. Print the table of contents at the beginning:

    \tableofcontents

  9. 在所有你想要的级别写标题。使用\addcontentsline\addtocontents手动添加内容到目录:

    \part{第一部分}

    \chapter*{前言}

    \addcontentsline{目录}{章节}{前言}

    \chapter{第一章}

    \section{一节}

    \section{另一部分}

    \subsection{较小的部分}

    \subsubsection[更深层次]{这个部分有一个

    甚至更深层次}

    \chapter{第二个主要章节}

    \part{第二部分}

    \chapter{第三个主要章节}

  10. Write headings in all the levels you want. Use \addcontentsline or \addtocontents to add something to the TOC manually:

    \part{First Part}

    \chapter*{Preface}

    \addcontentsline{toc}{chapter}{Preface}

    \chapter{First main chapter}

    \section{A section}

    \section{Another section}

    \subsection{A smaller section}

    \subsubsection[Deeper level]{This section has an

    even deeper level}

    \chapter{Second main chapter}

    \part{Second part}

    \chapter{Third main chapter}

  11. 结束附录有自己的章节:

    \附录

    \cleardoublepage

    \addtocontents{toc}{\bigskip}

    \addcontentsline{目录}{部分}{附录}

    \chapter{词汇表}

    \chapter{符号}

    \end{文档}

  12. Finish with an appendix that has its own chapters:

    \appendix

    \cleardoublepage

    \addtocontents{toc}{\bigskip}

    \addcontentsline{toc}{part}{Appendix}

    \chapter{Glossary}

    \chapter{Symbols}

    \end{document}

  13. 单击“排版”进行编译。第一页将显示内容但没有条目。
  14. Click on Typeset to compile. The first page will show Contents but no entries.
  15. 再次单击排版。现在我们可以看到目录:
  16. Click on Typeset a second time. Now we can see the table of contents:
图 8.1 – 目录示例

图 8.1 – 目录示例

Figure 8.1 – An example of a table of contents

我们构建了一个使用多个分段命令的文档。LaTeX 在第一次运行时读取了我们所有的分段命令,并创建了一个扩展名为.toc的文件。该文件包含目录中所有条目的命令和标题。在第一次运行时,该文件还不存在;因此,目录仍然是空的。

We structured a document using several sectioning commands. LaTeX read all of our sectioning commands in the first run and created a file with the .toc extension. This file contains the commands and the titles for all entries in the table of contents. During the first run, that file didn't exist yet; thus, the TOC remained empty.

在第二次运行期间,\tableofcontents命令读取.toc文件并打印 TOC。

During the second run, the \tableofcontents command read the .toc file and printed the TOC.

在此示例中,我们将 TOC 的深度提高了一个级别。我们为前言添加了一个类似章节的条目,并使用\addcontentsline插入了一个类似部分的标题,显示了附录的开头。通过\addtocontents,我们在后一个标题之前插入了一些空间。在以下部分中,我们将查看这些命令详细了解并了解有关定制的更多信息。

In this example, we raised the depth of the TOC by one level. We added a chapter-like entry for the preface and inserted a part-like heading showing the beginning of the appendix, using \addcontentsline. Through \addtocontents, we inserted some space before the latter heading. In the following sections, we will look at these commands in detail and learn more about customizing.

调整 TOC 的深度

Adjusting the depth of the TOC

这些是标准的切片命令及其所谓的 TOC 级别:

These are the standard sectioning commands and their so-called TOC level:

  • \part : -1 在bookreport类中,在 articlearticle中为 0
  • \part: -1 in the book and report classes, and 0 in the article class article
  • \chapter : 0(除了在article类中,因为没有article的章节)
  • \chapter: 0 (except in the article class, since there are no chapters with article)
  • \部分:1
  • \section: 1
  • \小节:2
  • \subsection: 2
  • \小节:3
  • \subsubsection: 3
  • \段落:4
  • \paragraph: 4
  • \小段:5
  • \subparagraph: 5

书籍报告类中,LaTeX 创建 TOC 条目直到第 2 级,直到\subsection级别。在文章类中,LaTeX 默认创建目录条目直到第 3 层,即直到\subsubsection层。在一本书中,这意味着,例如,\subsubsection不生成 TOC 条目。有一个代表级别的变量,即\tocdepth。它是一个整数变量,我们称之为计数器。要告诉 LaTeX 在 TOC 中包含小节,我们必须增加这个计数器。有两种调整计数器值的基本方法:

In the book and report classes, LaTeX creates TOC entries until level 2, until the \subsection level. In the article class, LaTeX creates TOC entries until level 3 by default, that is, until the \subsubsection level. In a book, this means, for example, that \subsubsection doesn't generate a TOC entry. There is a variable representing the level, namely, \tocdepth. It's an integer variable, which we call a counter. To tell LaTeX to include subsubsections in the TOC, we would have to raise this counter. There are two basic ways to adjust a counter value:

  • \setcounter{name}{n}名称计数器指定一个整数值n
  • \setcounter{name}{n} specifies an integer value of n for the name counter.
  • \addtocounter{name}{n}将n的整数值添加到名称计数器的值。要减少计数器,请为n选择一个负值。
  • \addtocounter{name}{n} adds the integer value of n to the value of the name counter. To decrease a counter, choose a negative value for n.

因此,以下命令将确保即使是\subparagraph也会给出目录条目:

Thus, the following command would ensure that even \subparagraph gives a TOC entry:

\setcounter{tocdepth}{5}

\setcounter{tocdepth}{5}

相反,使用\addcounter,您可以在不知道其数量的情况下提高或降低级别。

Using \addcounter instead, you may raise or lower the level without knowing its number.

相比之下对于命令,计数器名称不以反斜杠开头。

In contrast to commands, counter names don't begin with a backslash.

缩短条目

Shortening entries

如你已经在第 3 章设计页面中学习过,您可以为目录选择不同于正文标题的文本。每个分节命令都理解 TOC 条目的可选参数,如果您希望使用很长的标题,这将特别有用。不过,较短的 TOC 条目就足够了。在我们的示例中,我们通过以下命令完成此操作:

As you have already learned in Chapter 3, Designing Pages, you may choose a text for the TOC different from the heading in the body text. Each sectioning command understands an optional argument for the TOC entry, which is especially useful if you wish to use very long headings. Still, a shorter TOC entry would be sufficient. In our example, we did this by means of the following command:

\subsubsection[更深层次]{这个部分有更深层次的

\subsubsection[Deeper level]{This section has an even deeper

等级}

level}

正文显示长标题,而 TOC 显示短标题。标题打印在顶部称为running titles 的页面也会使用短条目,因为标题中的空间非常有限。

The body text shows the long heading, while the TOC shows the short one. Titles printed at the top of the pages, called running titles, would use the short entry as well, as the space in headers is very limited.

手动添加条目

Adding entries manually

已加星标命令,例如\chapter*\section*,不会生成目录条目。在我们的示例中,我们使用以下命令手动执行此操作:

Starred commands, such as \chapter* and \section*, don't produce a TOC entry. In our example, we did that manually by using this command:

\addcontentsline{文件扩展名}{部分单位}{文本}

\addcontentsline{file extension}{sectional unit}{text}

我们可以在多种情况下使用此命令。文件扩展名可能如下:

We can use this command in several contexts. The file extension could be the following:

  • toc目录文件
  • toc for the table of contents file
  • lof用于图形文件列表
  • lof for the list of figures file
  • 表文件列表的批次
  • lot for the list of tables file

或者,它可以是 LaTeX 已知的文件类型的任何此类扩展名。

Alternatively, it could be any such extension of a file type known to LaTeX.

部分单位确定条目的格式。它指定章节以创建格式类似于常规章节条目的条目,对于其他部分单元(如部分、部分或小节)也类似。

sectional unit determines the formatting of the entry. It specifies the chapter to create an entry that is formatted like a regular chapter entry, and similarly for other sectional units such as part, section, or subsection.

第三个参数包含条目的文本。

The third argument contains the text for the entry.

您可以借助以下命令更直接地插入文本或命令:

You may insert text or commands more directly with the help of the following command:

\addtocontents{文件扩展名}{entry}

\addtocontents{file extension}{entry}

\addcontentsline相反,参数条目直接写入文件而无需任何额外的格式。您可以选择任何您喜欢的格式。

Contrary to \addcontentsline, the argument entry is written directly to the file without any additional formatting. You may choose any formatting you like.

我们可以还可以使用\addtocontents命令进行一些自定义,例如:

We can also use the \addtocontents command for some customization, for example:

  • \addtocontents{toc}{\protect\enlargethispage {\baselineskip}}扩展文本高度,使得额外的一行适合内容页面。
  • \addtocontents{toc}{\protect\enlargethispage {\baselineskip}} extends the text height such that one additional line fits to the contents page.
  • \addtocontents{toc}{\protect\newpage}导致目录中的分页符。例如,如果自动分页发生在章节条目之后和后续章节条目之前,您可能希望在章节条目之前强制分页。
  • \addtocontents{toc}{\protect\newpage} causes a page break in the TOC. For instance, if the automatic page break happens after a chapter entry and before the following section entries, you might wish to force a page break already before the chapter entry.
  • \addtocontents{toc}{\protect\thispagestyle{fancy}}将当前目录页面的页面样式更改为fancy。由于章节的第一页默认为普通样式,目录的第一页也将是普通的,即使您指定了\pagestyle{fancy}。\ addtocontents {toc}{\protect \thispagestyle{fancy}}命令覆盖它。
  • \addtocontents{toc}{\protect\thispagestyle{fancy}} changes the page style of the current TOC page to fancy. As the first page of a chapter is of the plain style by default, the first page of the TOC would be plain as well, even if you specified \pagestyle{fancy}. The \addtocontents{toc}{\protect \thispagestyle{fancy}} command overrides it.

将此类命令放在它们应该有效的地方。要影响目录的第一页,请将其放在文档的开头。要在特定章节之前引起分页,请将其放在相应的\chapter调用之前。

Place such commands where they should be effective. To affect the first TOC page, place it at the beginning of your document. To cause a page break before a specific chapter, put it right before the corresponding \chapter call.

创建和自定义图形列表

Creating and customizing lists of figures

作为简要地提及第 5 章中,包括图像,以及第 6 章创建表格中,创建图形和表格列表的两个命令是\listoffigures\listoftables。根据类别的不同,他们会生成所有标题的精美列表以及图片、表号和相应的页码。与 TOC 一样,LaTeX 可以自动完成所有工作。但是,我们可以使用相同的技术(例如 TOC)来自定义其他列表。让我们试试吧。

As briefly mentioned in Chapter 5, Including Images, and in Chapter 6, Creating Tables, the two commands for creating lists of figures and tables are \listoffigures and \listoftables. Depending on the class, they produce a fine list of all captions together with the figure, the table number, and the corresponding page numbers. As with the TOC, LaTeX can do everything automatically. However, we may use the same techniques, such as with the TOC, to customize the other lists. Let's try that.

假设我们所有的数字都是图表。我们将避免使用术语图,我们将添加图表列表:

Suppose all our figures are diagrams. We will avoid using the term figure, and we will add a list of diagrams:

  1. 打开我们当前的示例。将这些行添加到您的序言中:

    \renewcommand{\figurename}{图表}

    \renewcommand{\listfigurename}{图表列表}

  2. Open our current example. Add these lines to your preamble:

    \renewcommand{\figurename}{Diagram}

    \renewcommand{\listfigurename}{List of Diagrams}

  3. 在\tableofcontents之后,添加以下内容:

    \listoffigures

  4. Right after \tableofcontents, add the following:

    \listoffigures

  5. 在第一章某处加个图:

    \开始{图}

    \定心

    \fbox{图表占位符}

    \caption{企业组织图表}

    \结束{图}

  6. Add a diagram somewhere in the first chapter:

    \begin{figure}

    \centering

    \fbox{Diagram placeholder}

    \caption{Enterprize Organizational Chart}

    \end{figure}

  7. 在第三章的第二部分,我们想添加网络设计图。让我们在图表列表( LOF ) 中标记它,并让图表跟随:

    \addtocontents{lof}{网络图:}

    \开始{图}

    \定心

    \fbox{图表占位符}

    \caption{网络概览}

    \结束{图}

    \开始{图}

    \定心

    \fbox{图表占位符}

    \caption{无线局域网设计}

    \结束{图}

  8. In the second part of the third chapter, we'd like to add network design diagrams. Let's mark that in the list of figures (LOF) and let the diagrams follow:

    \addtocontents{lof}{Network Diagrams:}

    \begin{figure}

    \centering

    \fbox{Diagram placeholder}

    \caption{Network overview}

    \end{figure}

    \begin{figure}

    \centering

    \fbox{Diagram placeholder}

    \caption{WLAN Design}

    \end{figure}

  9. 点击排版两次得到文件和清单:
  10. Click on Typeset twice to get the document and the list:
图 8.2 – 图表列表

图 8.2 – 图表列表

Figure 8.2 – A list of diagrams

我们通过重新定义 LaTeX 宏来重命名图形和列表标题。在本章结束时,您将获得您可以重新定义的 LaTeX 类使用的名称列表。

We renamed the figures and the list heading by redefining LaTeX macros. At the end of this chapter, you will get a list of names used by LaTeX classes that you may redefine.

与 TOC 一样,我们使用\addtocontents命令在.lof文件中插入一个粗体标题,LaTeX 在其中收集标题。它的工作原理与 TOC 类似。

As with the TOC, we used the \addtocontents command to insert a bold heading into the .lof file, where LaTeX collects the captions. It works similarly to the TOC.

创建表列表

Creating a list of tables

你已知道你需要创造和customize a list of tables ( LOT ) 是 LaTeX 收集表格标题的文件,扩展名为.lot所以, \addtocontents的第一个参数是lot。一切都类似地工作,比如\listoftables\tablename\listtablename

You already know that all you need to create and customize a list of tables (LOT) is the file where LaTeX collects the tables' captions and has the .lot extension. So, the first argument of \addtocontents would be lot. Everything works analogously, like \listoftables, \tablename, and \listtablename.

使用包进行定制

Using packages for customization

除了描述的简单方法,包提供了用于自定义 TOC 和图表列表的复杂功能:

Besides the simple methods described, packages provide sophisticated features for customizing the TOC and the lists of figures and tables:

  • tocloft可以广泛控制 TOC、LOF 和LOT的排版。您甚至可以定义新类型的此类列表。
  • tocloft gives extensive control over the typography of TOC, LOF, and LOT. You may even define new kinds of such lists.
  • titletoc提供了方便的条目处理,并且是titlesec的伴侣,这是一个用于自定义章节标题的优秀包。
  • titletoc offers convenient handling of entries and is the companion to titlesec, an excellent package for customizing sectioning headings.
  • multitoc使用multicol包提供两列或更多列的布局。
  • multitoc offers a layout in two or more columns using the multicol package.
  • minitoc可以为每个部分、章节或小节创建小的 TOC。
  • minitoc can create small TOCs for each part, chapter, or section.
  • tocbibind可以自动将参考书目、索引、TOC、LOF 和 LOT 添加到目录中。它甚至可以使用编号标题代替默认的未编号标题。
  • tocbibind can automatically add a bibliography, index, TOC, LOF, and LOT to the table of contents. It's even capable of using numbered headings instead of the default unnumbered ones.

使用texdoc命令行工具或访问https://texdoc.org阅读包文档。

Use the texdoc command-line tool or visit https://texdoc.org to read the package documentation.

现在我们知道了如何创建我们通常放在文档开头的目录、表格和图表。现在让我们继续文档末尾的列表——关键字索引和参考书目。

Now we know how to create lists of contents, tables, and figures that we usually put at the beginning of a document. Let's now continue with lists that come at the end of a document – a keyword index and a bibliography.

生成索引

Generating an index

广泛的文档通常包含一个索引。索引是指向我们可以在文档中找到相关材料的位置的单词或短语和页码的列表。与全文搜索功能相比,该索引提供了指向相关信息的选择性指针。

Extensive documents often contain an index. An index is a list of words or phrases and page numbers pointing to where we can find related material in the document. In contrast to a full-text search feature, the index provides selective pointers to relevant information.

当轮到我们为索引识别和标记单词时,LaTeX 将收集此信息并排版索引。

When it's our turn to identify and mark the words for the index, LaTeX will collect this information and typeset the index.

假设我们的示例包含有关企业及其结构以及网络结构和设计的信息。我们将标记文本中出现这些概念的位置。最后,我们将命令LaTeX排版索引,如下:

Suppose our example contains information about an enterprise and its structure as well as its network structure and design. We will mark places in the text where these concepts occur. Finally, we will order LaTeX to typeset the index, as follows:

  1. 回到我们的例子。在序言中,加载索引包并添加创建索引的命令:

    \usepackage{索引}

    \制作索引

  2. Go back to our example. In the preamble, load the index package and add the command to create the index:

    \usepackage{index}

    \makeindex

  3. 在我们的企业图的标题中,用关键字enterprise索引这一点:

    \caption{\index{enterprise}企业组织

    图表}

  4. In the caption of our enterprise diagram, index this point with the keyword enterprise:

    \caption{\index{enterprise}Enterprise Organizational

    Chart}

  5. 在包含我们的图表的第三章中,通过关键字network索引:

    \index{网络}

  6. In the third chapter, which contains our diagrams, index by the keyword network:

    \index{network}

  7. 在\end{document}之前,为目录的索引创建一个条目。为确保它显示正确的页码,请结束它之前的页面:

    \clearpage

    \addcontentsline{toc}{chapter}{Index}

  8. Directly before \end{document}, create an entry for the index for the table of contents. To ensure that it shows the correct page number, end the page before it:

    \clearpage

    \addcontentsline{toc}{chapter}{Index}

  9. 在下一行中,命令 LaTeX 排版索引:

    \打印索引

  10. In the following line, order LaTeX to typeset the index:

    \printindex

  11. 如果您使用的是 TeXworks,请在排版按钮旁边的下拉框中选择MakeIndex而不是 pdfLaTeX 。然后,单击排版按钮。如果您使用其他编辑器,请使用其 MakeIndex 功能或在命令中键入以下内容在文档目录提示:

    makeindex 文件名

  12. If you're using TeXworks, choose MakeIndex instead of pdfLaTeX in the drop-down box next to the Typeset button. Then, click the Typeset button. If you use another editor, use its MakeIndex feature or type the following at the command prompt in the document directory:

    makeindex documentname

  13. 切换回 pdfLaTeX。单击Typeset,然后查看最后一页:
  14. Switch back to pdfLaTeX. Click on Typeset, and look at the last page:
图 8.3 – 索引

图 8.3 – 索引

Figure 8.3 – An index

我们加载了index包,它改进了 LaTeX 的内置索引功能。

We loaded the index package, which improves LaTeX's built-in indexing capabilities.

或者,您可以使用makeidx包,它是标准 LaTeX 的一部分。\makeindex命令准备索引。这两个命令都属于序言,因此应放在\begin{document}之前。

Alternatively, you could use the makeidx package, which is part of standard LaTeX. The \makeindex command prepares the index. Both commands belong to the preamble, so should be placed before \begin{document}.

\index命令只接受一个参数,即要索引的单词或短语。它将此短语写入扩展名为.idx的文件中。如果查看此文件,您会发现如下几行:

The \index command takes just one argument, namely, the word or the phrase to be indexed. It writes this phrase into a file with the .idx extension. If you look into this file, you will find lines such as the following:

\indexentry {企业} {9}

\indexentry {enterprise}{9}

\indexentry {网络} {15}

\indexentry {network}{15}

这些代表索引条目和相应的页码。

These stand for the index entries and the corresponding page numbers.

外部makeindex程序获取该.idx文件并生成一个.ind文件。后者包含用于创建索引的 LaTeX 代码。具体来说,它包含索引列表环境以及项目,如下所示:

The external makeindex program takes that .idx file and produces a .ind file. The latter consists of LaTeX code for the index creation. Specifically, it contains the index list environment together with the items and appears as follows:

\begin{theindex}

\begin{theindex}

\项目企业,9

\item enterprise, 9

\索引空间

\indexspace

\项目网络,15

\item network, 15

\end{theindex}

\end{theindex}

更复杂的索引可能包含子项目、页面范围和对其他项目的引用。让我们看看如何生成这样的索引。在本书的网站https://latexguide.org/chapter-08上,您可以找到包含示例的完全可编译代码我们将在以下部分中了解的命令。您可以直接在网页上试用它们。

More complex indexes may contain subitems, page ranges, and references to other items. Let's see how to produce such an index. At the book's website at https://latexguide.org/chapter-08, you can find fully compilable code containing example commands that we will get to know in the following sections. You can try them out directly on the web page.

定义索引条目和子条目

Defining index entries and subentries

我们有已经使用以下命令创建简单的索引条目:

We have already created simple index entries with the following command:

\index{短语}

\index{phrase}

我们可以通过指定主条目后跟子条目来生成子条目,以感叹号分隔,例如:

We can produce subentries by specifying the main entry followed by the subentry, separated by an exclamation mark, for example:

\index{网络!概览}

\index{network!overview}

此外,子条目可能有子条目;只需使用另一个符号,例如:

Also, subentries may have subentries; just use another ! symbol, for example:

\index{企业!组织}

\index{enterprise!organization}

\index{企业!组织!销售}

\index{enterprise!organization!sales}

\index{企业!组织!控制}

\index{enterprise!organization!controlling}

\index{企业!组织!运营}

\index{enterprise!organization!operation}

这最多可以达到三个级别。

This is possible up to three levels.

指定页面范围

Specifying page ranges

如果几个页面处理相同的概念,您可以为索引条目指定一个页面范围。在条目后缀|(范围开始的地方,并添加|)结束的地方。在网络章节的开头,添加|(如下:

If several pages deal with the same concept, you may specify a page range for the index entry. Suffix the entry with |( where the range starts, and add |) where it ends. At the beginning of the network chapter, add |( as follows:

\index{网络|(}

\index{network|(}

同时,在本章末尾添加|)如下:

While, at the end of this chapter, add |) as follows:

\index{网络|)}

\index{network|)}

这个结果在Network, 15-17形式的条目中。

This results in an entry of the form Network, 15-17.

在索引中使用符号和宏

Using symbols and macros in the index

makeindex排序按字母顺序排列的条目。如果您想在索引中包含符号,例如希腊字母、化学公式或数学符号,您可能会遇到将它们集成到排序中的问题。为此,\index理解排序键。使用此键作为条目的前缀,以@符号分隔,例如:

makeindex sorts the entries alphabetically. If you would like to include symbols in the index, for example, Greek letters, chemical formulas, or math symbols, you may encounter the problem of integrating them into the sorting. For this purpose, \index understands a sort key. Use this key as a prefix for the entry, separated by the @ symbol, for instance:

\index{伽玛@$\伽玛$}

\index{Gamma@$\Gamma$}

通常不建议对索引条目使用宏。宏名称(包括反斜杠)将决定排序,尽管宏会在索引中展开。假设你有一个代表 TeX 用户组的\group宏,定义如下:

Using macros for index entries is generally not recommended. The macro name, including the backslash, would determine the sorting, although the macro would be expanded in the index. Imagine you've got a \group macro that stands for TeX Users Group, defined like this:

\newcommand{\group}{\TeX\ 用户组}

\newcommand{\group}{\TeX\ Users Group}

如果您编写以下内容,那么 TeX Users Group 条目将在排序中被视为\group并且不会出现在以 T 开头的条目中:

If you write the following, then the TeX Users Group entry would be treated like \group in the sorting and won't appear among the entries beginning with T:

\索引{\组}

\index{\group}

但是,您可以通过添加排序键作为前缀来修复此类问题,例如:

However, you could repair such issues by adding a sort key as a prefix, such as here:

\index{TeX@\group}

\index{TeX@\group}

同样,您可以指示如何对具有特殊字符的单词进行排序。在这里,单词schön将像单词schon 一样排序:

Similarly, you can indicate how words with special characters will be sorted. Here, the word schön will be sorted like the word schon:

\index{schon@sch\"{o}n}

\index{schon@sch\"{o}n}

作为符号| @,和在索引条目中具有特殊含义,我们需要采取额外的步骤将它们打印为它们的原始符号含义。这是我们如何打印它们的示例:

As the symbols |, @, and ! have special meanings within index entries, we need to take an extra step to print them as their original symbol meaning. That's an example of how we can print them:

\index{感叹号(“!)!大声}

\index{exclamation ("!)!loud}

我们可以打印符号| @,和在索引中引用它们,使用前面的"

We can print the symbols |, @, and ! in the index by quoting them, using a preceding ".

引用其他索引条目

Referring to other index entries

不同的词可能代表同一个概念。对于这种情况,可以在没有页码的情况下添加对主要短语的交叉引用。添加代码|see{entry list}可以实现这一点,例如:

Different words may stand for the same concept. For such cases, it's possible to add a cross-reference to the main phrase without a page number. Adding the code |see{entry list} achieves that, for example:

\index{无线|参见{WLAN}}

\index{wireless|see{WLAN}}

\index{无线局域网}

\index{WLAN}

因此,参考文献不打印页码,因此它们在文本中的位置无关紧要。您可以将它们收集在文档的一个位置。

As such, references don't print a page number, so their position in the text doesn't matter. You could collect them in one place of your document.

微调页码

Fine-tuning page numbers

如果一个索引条目涉及多个页面,您可能想要强调特定的页码以表明它是主要参考。您可以定义一个强调命令,如下所示:

If an index entry refers to several pages, you might want to emphasize a specific page number to indicate it as the primary reference. You could define a command for emphasizing as follows:

\newcommand{\main}[1]{\emph{#1}}

\newcommand{\main}[1]{\emph{#1}}

并且,对于索引条目,添加管道符号和命令名称:

And, for the index entry, add a pipe symbol and the command name:

\index{无线局域网|主}

\index{WLAN|main}

因此,LaTeX 会强调相应的页码。简单地写\index{WLAN|emph}\index{WLAN|texbf}也是可能的。但是,定义您自己的宏更为一致——记住分离形式和内容的概念。

Thus, LaTeX emphasizes the corresponding page number. Simply writing \index{WLAN|emph} or \index{WLAN|texbf} is possible as well. However, defining your own macro is more consistent—remember the concept of separating form and content.

设计索引布局

Designing the index layout

如果我们延长我们的示例文档包含前面部分中提到的示例命令,\printindex为我们提供了这个布局,包含子条目、范围、引用和强调的条目:

If we extend our example document with the example commands mentioned in the previous sections, \printindex gives us this layout, containing subentries, ranges, references, and emphasized entries:

图 8.4 – 更复杂的索引

图 8.4 – 更复杂的索引

Figure 8.4 – A more complex index

LaTeX 提供了一些索引样式,称为latex(默认)、ginddiniso。使用另一个样式,使用makeindex程序的-s选项指定它,例如:

LaTeX provides some index styles called latex (the default), gind, din, and iso. To use another style, specify it using the –s option of the makeindex program, for example:

makeindex –s iso 文件名

makeindex –s iso documentname

如果您在此调用后进行编译,索引布局将更改为以下内容:

If you compile after this call, the index layout changes to the following:

图 8.5 – iso 样式的索引

图 8.5 – iso 样式的索引

Figure 8.5 – An index with the iso style

您甚至可以定义自己的样式。要了解有关索引和makeindex的更多信息,请在命令提示符下使用texdoc :

You could even define your own styles. To learn more about indexing and makeindex, use texdoc at the command prompt:

文本文档索引

texdoc index

有关makeindex工具的更多信息,请使用以下命令:

For more information about the makeindex tool, use the following command:

texdoc 生成索引

texdoc makeindex

或者,访问https://texdoc.org/pkg/indexhttps://texdoc.org/pkg/makeindex上的在线文档。

Or, visit the documentation online at https://texdoc.org/pkg/index or https://texdoc.org/pkg/makeindex.

虽然在编写文档时生成索引似乎很自然,但这可能会导致索引不一致。建议先写完再搞清楚什么应该出现在索引中。

Although it seems natural to generate the index while writing the document, this might lead to inconsistencies in the index. It's first recommended to finish writing and then to work out what should appear in the index.

我们的下一个列表主题是打印列表引用,即参考书目。

Our next list topic is printing the list references, that is, the bibliography.

创建参考书目

Creating a bibliography

科学的特别是文件通常包含参考文献列表或参考书目。我们将研究如何排版参考书目以及如何引用其条目。

Scientific documents in particular commonly contain a list of references or a bibliography. We will work out how to typeset a bibliography and how to refer to its entries.

使用 LaTeX 的标准功能,我们将创建一个小的参考列表,其中包含 TeX 的创建者 Donald E. Knuth 的一本书和一篇文章。在我们的正文中,我们将同时提及:

Using LaTeX's standard features, we will create a small list of references containing a book and an article by Donald E. Knuth, the creator of TeX. In our body text, we will refer to both:

  1. 创造新文件如下:

    \文档类{文章}

    \开始{文档}

    \section*{推荐文本}

    要深入研究 \TeX\,请参阅 \cite{DK86}。

    关于编写数学文本,请参阅 \cite{DK89}。

    \begin{参考书目}{8}

    \bibitem{DK86} DE Knuth, \emph{The {\TeX}book}, 1986

    \bibitem{DK89} DE Knuth, \emph{排版具体

    数学}, 1989

    \end{书目}

    \end{文档}

  2. Create a new document as follows:

    \documentclass{article}

    \begin{document}

    \section*{Recommended texts}

    To study \TeX\ in depth, see \cite{DK86}.

    For writing math texts, see \cite{DK89}.

    \begin{thebibliography}{8}

    \bibitem{DK86} D.E. Knuth, \emph{The {\TeX}book}, 1986

    \bibitem{DK89} D.E. Knuth, \emph{Typesetting Concrete

    Mathematics}, 1989

    \end{thebibliography}

    \end{document}

  3. 单击排版并检查输出:
  4. Click on Typeset and examine the output:
图 8.6 – 参考列表

图 8.6 – 参考列表

Figure 8.6 – A list of references

我们使用了一个称为thebibliography的环境来排版参考列表,这类似于我们在第 4 章创建列表中看到的描述列表。此列表中的每个项目都有一个密钥。为了在正文中引用,我们提到了那个键使用\cite命令。让我们详细看看这些命令。

We used an environment called thebibliography to typeset the list of references, which is similar to a description list as we've seen in Chapter 4, Creating Lists. Each item on this list has got a key. For the purpose of citing in the body text, we referred to that key using the \cite command. Let's look at these commands in detail.

使用标准书目环境

Using the standard bibliography environment

LaTeX 的标准书目环境具有以下形式:

LaTeX's standard environment for bibliographies has the following form:

\begin{thebibliography}{最宽的标签}

\begin{thebibliography}{widest label}

\bibitem[label]{key} 作者、标题、年份等。

\bibitem[label]{key} author, title, year etc.

\bibitem…

\bibitem…

……

\end{书目}

\end{thebibliography}

每个项目都使用\bibitem命令指定。此命令需要一个确定密钥的强制参数。我们可以简单地用\cite{key}\cite{key1,key2}来引用这个键。\cite接受一个可选参数,说明页面范围,例如\cite[p.\,18--20]{key}。您可以通过\bibitem的可选参数选择标签。如果我们没有声明标签,LaTeX 会在方括号中对项目进行连续编号,如图8.6所示。

Each item is specified using the \bibitem command. This command requires a mandatory argument determining the key. We may simply refer to this key with \cite{key} or \cite{key1,key2}. \cite accepts an optional argument stating a page range, for example, \cite[p.\,18--20]{key}. You may choose a label by means of the optional argument of \bibitem. If we did not state a label, LaTeX would number the items consecutively in square brackets, as we've seen in Figure 8.6.

使用标签,环境可能如下所示:

Using labels, the environment could look as follows:

\begin{thebibliography}{Knuth89}

\begin{thebibliography}{Knuth89}

\bibitem[Knuth86]{DK86} DE Knuth, \emph{The {\TeX}book}, 1986

\bibitem[Knuth86]{DK86} D.E. Knuth, \emph{The {\TeX}book}, 1986

\bibitem[Knuth89]{DK89} DE Knuth, \emph{排版具体

\bibitem[Knuth89]{DK89} D.E. Knuth, \emph{Typesetting Concrete

数学}, 1989

Mathematics}, 1989

\end{书目}

\end{thebibliography}

相应的输出是这样的:

And the corresponding output is this:

图 8.7 – 参考列表

图 8.7 – 参考列表

Figure 8.7 – A list of references

如您所见,LaTeX 自动将\cite的输出调整为新标签。cite包提供压缩和排序的数字引用列表,例如[2,4-6]文内引用的进一步格式化选项。

As you can see, LaTeX adjusted the output of \cite to the new labels automatically. The cite package offers compressed and sorted lists of numerical citations, such as [2,4-6], and further formatting options for in-text citations.

环境的强制项应包含最宽的标签以对齐项。因此,例如,如果您有超过 9 个但少于 100 个项目,您可以在参数中写入两位数字。

The mandatory item of the environment should contain the widest label for the alignment of the items. So, for instance, if you have more than 9 but fewer than 100 items, you may write two digits into the argument.

在 BibTeX 中使用书目数据库

Using bibliography databases with BibTeX

手动创建参考书目很费力。尤其如果您在多个文档中使用参考文献,那么使用数据库并让程序为您生成参考书目将是有益的。这听起来比实际情况更复杂。让我们试试这个。

Manually creating the bibliography is laborious. Especially if you use references in several documents, it would be beneficial to use a database and let a program generate the bibliography for you. This sounds more complicated than it actually is. Let's try this.

我们将创建一个单独的数据库文件,其中包含我们之前示例的引用。我们将修改示例以使用该数据库。为了使这个数据库可用,我们必须调用外部名为BibTeX 的程序:

We will create a separate database file containing the references of our previous example. We will modify our example to use that database. To make this database usable, we have to call the external program called BibTeX:

  1. 创建一个新文档。首先编写 TeXbook 的条目:

    @book{DK86,

    author = "DE Knuth",

    title = "{\TeX} 书",

    publisher = "艾迪生卫斯理",

    年份 = 1986

    }

  2. Create a new document. Begin by writing the entry for the TeXbook:

    @book{DK86,

    author = "D.E. Knuth",

    title = "The {\TeX}book",

    publisher = "Addison Wesley",

    year = 1986

    }

  3. 为了下一个条目,即文章,我们将指定更多字段:

    @article{DK89,

    author = "DE Knuth",

    title = "排版具体数学",

    journal = "TUGboat",

    体积 = 10,

    数 = 1,

    页数 = "31--36",

    月 = 四月,

    年份 = 1989

    }

  4. For the next entry, that is, the article, we will specify even more fields:

    @article{DK89,

    author = "D.E. Knuth",

    title = "Typesetting Concrete Mathematics",

    journal = "TUGboat",

    volume = 10,

    number = 1,

    pages = "31--36",

    month = apr,

    year = 1989

    }

  5. 保存文件并将其命名为example.bib。打开我们的示例文档,修改如下:

    \文档类{文章}

    \开始{文档}

    \section*{推荐文本}

    要深入研究 \TeX\,请参阅 \cite{DK86}。为了写数学课文,

    参见 \cite{DK89}。

    \bibliographystyle{alpha}

    \书目{例子}

    \end{文档}

  6. Save the file and give it the name example.bib. Open our example document and modify it as follows:

    \documentclass{article}

    \begin{document}

    \section*{Recommended texts}

    To study \TeX\ in depth, see \cite{DK86}. For writing math texts,

    see \cite{DK89}.

    \bibliographystyle{alpha}

    \bibliography{example}

    \end{document}

  7. 点击一次Typeset with pdfLaTeX。如果您使用的是 TeXworks,请选择 BibTeX 而不是 pdfLaTeX,出现在Typeset按钮旁边的下拉框中,然后单击Typeset。如果您正在使用其他编辑器编写,请使用其 BibTeX 选项或在文档目录中的命令提示符下键入,如下所示:

    bibtex 文件名

  8. Click on Typeset one time with pdfLaTeX. If you're using TeXworks, choose BibTeX instead of pdfLaTeX, present in the drop-down box next to the Typeset button, and then click on Typeset. If you are writing with another editor, use its BibTeX option or type at the command prompt in the document directory as follows:

    bibtex documentname

  9. 点击使用pdfLaTeX排版两次。这是结果:
  10. Click on Typeset twice with pdfLaTeX. Here's the result:
图 8.8 – 基于数据库文件的参考书目

图 8.8 – 基于数据库文件的参考书目

Figure 8.8 – A bibliography based on a database file

我们创建了一个包含所有参考书目条目的文本文件。在下一节中,我们将深入研究它的格式。我们的文档选择了一种称为alpha的样式,它根据作者姓名对条目进行排序,并使用由作者年份组成的快捷方式作为标签。然后我们告诉 LaTeX 加载名为example的参考书目文件。.bib扩展名已自动添加。

We created a text file containing all bibliography entries. In the next section, we will look at its format in depth. Our document chose a style called alpha, which sorts entries according to the author's name and uses a shortcut consisting of author and year as the label. Then we told LaTeX to load the bibliography file called example. The .bib extension has been added automatically.

之后,我们调用了外部程序 BibTeX。这个程序从 example.tex 文件知道example.bib必须翻译。因此,在这个.bib文件之外,它创建了一个.bbl文件,其中包含 LaTeX参考书目环境和最终条目。

Afterward, we called the external program BibTeX. This program knows from the example .tex file that example.bib has to be translated. Thus, out of this .bib file, it creates a .bbl file containing a LaTeX thebibliography environment and the final entries.

最后,我们不得不编译两次,以确保所有的交叉引用都是正确的。

Finally, we had to compile twice, to ensure that all the cross-references are correct.

虽然我们需要更多的步骤来生成参考书目,但也有好处——我们不需要微调每个条目。我们可以轻松地在样式之间切换。然后我们可以重用.bib文件。

Though we need some more steps to generate the bibliography, there are also benefits – we don't need to fine-tune each entry. We can easily switch between styles. We can then reuse the .bib file.

那么,让我们看看.bib文件格式。它支持各种条目类型,例如bookarticle此外,这些条目包含authortitleyear等字段。让我们第一的查看支持的字段,然后我们将讨论不同类型的条目。

So, let's look at the .bib file format. It supports various entry types, such as book and article. Furthermore, these entries contain fields such as author, title, and year. Let's first look at the supported fields, and afterward, we will talk about the different kinds of entries.

查看 BibTeX 输入字段

Looking at the BibTeX entry fields

这是一个列表的标准领域。有些字段很常见,有些很少使用——我们将按照 BibTeX 文档的字母顺序列出它们:

Here's a list of the standard fields. Some fields are common, some are rarely used—we will just list them in alphabetical order, following the BibTeX documentation:

  • address:通常是发布者的地址。至少对于小型出版商而言,此信息可能会有用。
  • address: Usually, the address of the publisher. At least for small publishers, this information might be useful.
  • annote:标准参考书目样式未使用的注释。其他样式或宏可能会使用它。
  • annote: An annotation not used by the standard bibliography styles. Other styles or macros might use this.
  • author:作者的姓名。
  • author: The name(s) of the author(s).
  • booktitle:如果您引用其中的一部分,则为书名。您也可以改用标题字段。
  • booktitle: The title of a book if you cite a part of it. You can also use the title field instead.
  • 章节:章节编号。
  • chapter: A chapter number.
  • crossref:被交叉引用的数据库条目的键。
  • crossref: The key of the database entry being cross-referenced.
  • edition:一本书的版本(第一版、第二版等)。通常,它是大写的。
  • edition: The edition (first, second, and suchlike) of a book. Commonly, it is capitalized.
  • editor:编辑的姓名。
  • editor: The name(s) of the editor(s).
  • howpublished:发布方式,尤其是在不寻常的情况下。首字母大写。
  • howpublished: The way of publishing, especially if it's unusual. Capitalize the first word.
  • institution:这可能是赞助机构。
  • institution: This could be a sponsoring institution.
  • journal : 期刊名称;你可以使用常见的缩写。
  • journal: A journal name; you may use common abbreviations.
  • key:如果缺少作者信息,则用于按字母顺序排列、交叉引用和标记。不要将它与\cite命令中使用的键混淆,它对应于条目的开头。
  • key: Used for alphabetizing, cross-referencing, and labeling if the author's information is missing. Don't confuse it with the key used in the \cite command, which corresponds to the beginning of the entry.
  • month:作品发表或写作的月份(如果尚未发表)。通常使用三个字母的缩写。
  • month: The month in which the work was published or written if it's not yet published. Usually, a three-letter abbreviation is used.
  • 注意:任何其他有用的信息。首字母大写。
  • note: Any additional useful information. Capitalize the first word.
  • 号码期刊编号或系列中的另一种作品。
  • number: The number of a journal or another kind of work in a series.
  • organization:这可以是发起组织。
  • organization: This can be a sponsoring organization.
  • pages:页码或页码范围,例如 12-18 或 22+。
  • pages: A page number or range of page numbers, such as 12-18 or 22+.
  • 发布者:发布者的名称。
  • publisher: The name of the publisher.
  • school:可以是编写文档的学校的名称。
  • school: Could be the name of the school where the document was written.
  • Series:系列书籍的名称或多卷集中的编号。
  • Series: The name of a series of books or its number in a multi-volume set.
  • title:作品的标题。
  • title: The title of the work.
  • type:发布的类型。
  • type: The type of the publication.
  • :期刊或多卷书的卷。
  • volume: The volume of a journal or multi-volume book.
  • year:出版年份,如果尚未出版,则为写作年份。通常使用四个数字,例如 2010。您可以使用其他样式可能支持但标准样式忽略的任何字段。
  • year: The year of the publication or the year when it was written if it hasn't been published yet. Generally, four numerals are used, such as 2010. You may use any fields possibly supported by other styles and ignored by standard styles.

您可以通过在命令行键入texdoc bibtex或访问https://texdoc.org/pkg/bibtex来阅读 BibTeX 文档。

You can read the BibTeX documentation by typing texdoc bibtex at the command line or visiting https://texdoc.org/pkg/bibtex.

参考互联网资源

Referring to Internet resources

今天我们经常参考在线资源。到将 Internet 地址放入 BibTeX 字段,使用urlhyperref包的\url命令,例如:

Today, we often refer to online sources. To put internet addresses into BibTeX fields, use the \url command of the url or hyperref package, for example:

如何发布 = {\url{https://latex.org}}

howpublished = {\url{https://latex.org}}

有些样式提供了一个url字段,可以隐式地将内容格式化为 URL,因此我们不需要在那里使用\url命令。

Some styles offer a url field that formats the content as URL implicitly, so we don't need to use the \url command there.

了解 BibTeX 条目类型

Understanding BibTeX entry types

首先,你决定要添加的条目类型,然后您填写字段。不同的类型可能支持不同的领域。有些字段是必需的,有些是可选的,可以省略,有些在样式不支持时会被忽略。

Firstly, you decide which entry type you want to add, and then you fill in the fields. Different types may support various fields. Some fields are required, some are optional and may be omitted, and some are simply ignored when the style doesn't support it.

通常,条目的名称会告诉您它的含义。根据 BibTeX 参考,这些是标准条目类型及其必填和可选字段:

Usually, the name of the entry tells you its meaning. These are the standard entry types and their required and optional fields, according to the BibTeX reference:

图 8.9 – BibTeX 条目类型和字段

图 8.9 – BibTeX 条目类型和字段

Figure 8.9 – BibTeX entry types and fields

看一看在 BibTeX 参考中输入更多详细信息命令提示符下的以下内容:

Have a look at the BibTeX reference for more details by typing the following at the command prompt:

texdoc 中文提供

texdoc bibtex

或者,您可以访问https://texdoc.org/pkg/bibtex

Alternatively, you can visit https://texdoc.org/pkg/bibtex.

如果没有其他条目适合,请选择misc。对于类型,使用大写字母或小写字母都没有关系;@ARTICLE与@article的理解相同。如示例所示,条目具有以下形式:

If no other entry fits, choose misc. For the type, it doesn't matter if you use capitals or small letters; @ARTICLE is understood the same as @article. As the example shows, entries have the following form:

@entrytype{关键词,

@entrytype{keyword,

fieldname = {字段文本},

fieldname = {field text},

fieldname = {字段文本},

fieldname = {field text},

……

}

}

在字段文本周围使用大括号。也支持直引号,如在"field text"中。对于数字,您可以省略大括号。

Use braces around field text. Straight quotes instead, as in "field text", are also supported. For numbers, you may omit the braces.

某些样式会更改大写字母,这可能会导致不需要的小写字母。为了防止字母或单词变成小写,请在它们周围放置额外的大括号。最好围绕一个单词而不是仅仅围绕字母来保持连字和间距改进。例如,{WAL}看起来比{W}AL好,因为在标准文本流中,LaTeX 将 A移近前面的W。分开的大括号阻碍了 LaTeX 的微排版改进。

Some styles change the capitalization, which might lead to undesired lowercase letters. To protect letters or words from becoming lowercase, put additional braces around them. Preferably do it around a word instead of just the letter to keep ligatures and for spacing improvement. For example, {WAL} looks better than {W}AL, because in a standard text flow, LaTeX moves an A closer to a preceding W. Separating braces hampers LaTeX's micro-typographic improvements.

选择书目风格

Choosing the bibliography style

标准样式如下:

Standard styles are as follows:

  • plain:阿拉伯数字用于标签,根据作者姓名排序。该数字写在方括号中,也与\cite一起出现。
  • plain: Arabic numbers are used for the labels, sorted according to the names of the authors. The number is written in square brackets, which also appear with \cite.
  • unsrt:没有排序。所有条目看起来都像是在文本中被引用过的。否则,它看起来像plain
  • unsrt: There's no sorting. All entries appear like they were cited in the text. Otherwise, it looks like plain.
  • alpha:根据作者姓名实现排序;标签是包含作者姓名和出版年份的快捷方式。此外,这里使用方括号。
  • alpha: Sorting is realized according to the names of the authors; the labels are shortcuts comprising the author's name and the year of publication. Also, square brackets are used here.
  • abbrv:这类似于plain,但名字和其他字段条目是缩写的。样式应在\begin{document}之后和\bibliography之前选择。您可以在\bibliography之前写\ bibliographystyle以将它们放在一起。
  • abbrv: This is like plain, but first names and other field entries are abbreviated. The style should be chosen after \begin{document} and before \bibliography. You may write \bibliographystyle right before \bibliography to keep it together.

在 TeX 发行版和 Internet 上有更多可用的样式。例如,natbib包提供样式和在漂亮的作者年份方案中引用的能力。此包进一步添加了一些字段,例如ISBNISSNURL

There are more styles available in TeX distributions and on the Internet. For instance, the natbib package provides styles and the capability to cite in a nice author-year scheme. This package further adds some fields, such as ISBN, ISSN, and URL.

您可以尝试使用natbib包并使用其plainnatabbrvnatunsrtnat样式,例如:

You could give the natbib package a try and use its plainnat, abbrvnat, and unsrtnat styles, for instance:

\usepackage{natbib}

\usepackage{natbib}

\bibliographystyle{plainnat}

\bibliographystyle{plainnat}

这些行将改变我们的例子如下:

These lines would change our example as follows:

  • natbib重新实现了\cite命令并提供了变体,主要目的是支持作者年份引用。它适用于大多数其他可用样式。
  • natbib reimplemented the \cite command and offers variations to it, with the main purpose of supporting author-year citations. It works with most other available styles.
  • natbib介绍引用命令\citet用于文本引用,而\citep命令用于括号引用。有星号变体打印完整的作者列表,以及允许在前后添加文本的可选参数。
  • natbib introduces the citation command, \citet, for textual citations, and the \citep command for parenthetical citations. There are starred variants that print the full author list, and optional arguments that allow the addition of text before and after.

如果您想从这个优秀的软件包中受益,请查看文档。像往常一样,在命令行输入texdoc natbib或访问https://texdoc.org/pkg/natbib

Check out the documentation if you would like to benefit from this excellent package. As usual, type texdoc natbib at the command line or visit https://texdoc.org/pkg/natbib.

biblatex包提供了 BibTeX 和 LaTeX 提供书目功能的完整重新实现。biblatex不需要学习 BibTeX 语言,它可以与一个名为biber的程序一起使用,该程序取代了 BibTeX。在LaTeX Cookbook第 7 章目录、索引和参考书目中,您可以阅读涉及biblatexbiber的详细解释的分步示例。

The biblatex package provides a complete reimplementation of the bibliographic features offered by BibTeX and LaTeX. biblatex doesn't require learning the BibTeX language and it works with a program called biber, which replaces BibTeX. In the LaTeX Cookbook, Chapter 7, Contents, Indexes, and Bibliographies, you can read a well-explained step-by-step example involving biblatex and biber.

列出参考文献而不引用

Listing references without citing

BibTeX 需要只有那些在文本中引用并打印出来的数据库中的参考文献。但是,您可以为引用指定键,这些键仍然应该出现。随便写下以下,供参考:

BibTeX takes only those references from the database that are cited in the text and prints them out. However, you may specify keys for references, which should appear nevertheless. Just write the following for a single reference:

\nocite{键}

\nocite{key}

或者,编写以下内容以列出完整的数据库:

Or, write the following to list the complete database:

\nocite{*}

\nocite{*}

如果您不想在参考书目中包含您从未在文档中引用过的参考文献,请确保在文档的最终版本中删除\nocite{*} 。

Make sure to remove \nocite{*} in the final version of the document if you don't want to have references in the bibliography that you never cited in the document.

现在我们知道如何创建这样的表、列表、索引和参考书目,让我们做最后的看看如何自定义它们。

Now that we know how to create such tables, lists, indexes, and bibliographies, let's have a final look at how to customize them.

更改标题

Changing the headings

正如我们的图 8.2中的图表示例,如果您不喜欢标题内容,您可以轻松更改它。LaTeX 将标题文本存储在\contentsname文本宏中。所以,只需重新定义它如下:

As in our diagram example in Figure 8.2, if you don't like the heading Contents, you could easily change it. LaTeX stores the text of the heading in the \contentsname text macro. So, just redefine it as follows:

\renewcommand{\contentsname}{目录}

\renewcommand{\contentsname}{Table of Contents}

以下是此类宏及其默认值的列表:

Here's a list of such macros and their default values:

  • \contentsname:内容
  • \contentsname: Contents
  • \listfigurename:图形列表
  • \listfigurename: List of figures
  • \listtablename:表格列表
  • \listtablename: List of tables
  • \bibname:参考书目(在书籍报告类中)
  • \bibname: Bibliography (in the book and report classes)
  • \refname:参考文献(在文章类中)
  • \refname: References (in the article class)
  • \索引名称:索引
  • \indexname: Index

此外,正如所承诺的,这里是 LaTeX 使用的名称的其他宏列表,及其默认值:

Furthermore, as promised, here's a list of other macros for names used by LaTeX, with their default values:

  • \图名:图
  • \figurename: Figure
  • \表名:表
  • \tablename: Table
  • \零件名称:零件
  • \partname: Part
  • \章节名称:章节
  • \chaptername: Chapter
  • \abstractname : 摘要
  • \abstractname: Abstract
  • \附录名称:附录
  • \appendixname: Appendix

这并不奇怪!当您使用另一种语言编写时,使用名称宏特别有用。例如,babel包采用语言选项并根据所选语言重新定义所有这些名称宏。

This is not really surprising! Using name macros is especially useful when you write in another language. For instance, the babel package takes a language option and redefines all those name macros according to the chosen language.

然而,他们在选择缩写如Fig.或不同的措辞时也很有用,例如Appendices而不是Appendix

However, they are also useful when choosing abbreviations such as Fig. or different phrasing, such as Appendices instead of Appendix.

概括

Summary

在本章中,我们处理了多种列表。具体来说,我们学习了如何生成和自定义目录、图表列表、生成指向关键字和短语相关信息的索引,以及手动和使用书目数据库创建书目。

In this chapter, we dealt with many kinds of lists. Specifically, we learned about generating and customizing the table of contents, lists of figures and tables, producing an index pointing to relevant information for keywords and phrases, and creating bibliographies, both manually and using a bibliography database.

这些列表将引导您找到您正在寻找的信息。它们不仅仅是为了列出和总结。这就是为什么图表列表和表格列表的标题通常不会出现在 TOC 中,因为它们直接跟在 TOC 之后。有时,甚至有一个奇怪的要求,即在其自身中列出目录。如果您不确定设计或需求,请查看您特定领域的一本好书,看看示例性的目录、列表和索引可能是什么样子。

These lists will guide you to the information that you are looking for. They aren't just for listing and summarizing. That's why the headings of the list of figures and the list of tables usually don't appear in the TOC, as they directly follow the TOC. Sometimes, there's even the strange requirement to list the table of contents within itself. If you are not sure about a design or a requirement, have a look at a good book in your particular field to see what exemplary tables of contents, lists, and indexes might look like.

在下一章中,我们将深入研究科学写作。

In the next chapter, we will look at scientific writing in depth.

第 9 章:编写数学公式

Chapter 9: Writing Math Formulas

在本书的开头,在第 1 章“LaTeX 入门”中,我们承诺 LaTeX 可以提供卓越的数学排版质量。现在是时候证明这一点了。到本章结束时,你将能够写出漂亮的数学文本。

At the beginning of this book, in Chapter 1, Getting Started with LaTeX, we promised that LaTeX offers excellent quality for mathematical typesetting. Now it's time to prove this. By the end of this chapter, you will be able to write beautiful mathematical texts.

为了受益于 LaTeX 的数学功能,我们现在将处理以下内容:

To benefit from LaTeX's math capabilities, we shall now deal with the following:

  • 编写基本公式
  • Writing basic formulas
  • 排版多行公式
  • Typesetting multi-line formulas
  • 探索丰富的数学符号
  • Exploring the wealth of math symbols
  • 建立数学结构
  • Building math structures

这是一项艰巨的任务——让我们来解决它!

That's a tremendous undertaking—let's tackle it!

技术要求

Technical requirements

您可以使用本地 LaTeX 安装,也可以在https://latexguide.org/chapter-09在线编译示例代码。

You can use a local LaTeX installation, or you can compile the example code online at https://latexguide.org/chapter-09.

GitHub 上提供了代码: https: //github.com/PacktPublishing/LaTeX-Beginner-s-Guide-2nd-Edition-/tree/main/Chapter_09_-_Writing_Math_Formulas

The code is available on GitHub: https://github.com/PacktPublishing/LaTeX-Beginner-s-Guide-2nd-Edition-/tree/main/Chapter_09_-_Writing_Math_Formulas.

在本章中,我们将使用以下包:amsmathamssymbgeometrylatexsymupgreek

In this chapter, we will use the following packages: amsmath, amssymb, geometry, latexsym, and upgreek.

此外,我们将简要讨论这些包:amsthmdsfontgraphicxmathtoolsntheoremsiunitxxitszapfino

Furthermore, we will briefly discuss these packages: amsthm, dsfont, graphicx, mathtools, ntheorem, siunitx, xits, and zapfino.

您可以在第 10 章LaTeX Cookbook高级数学中找到更多代码示例,该书的网站上有可编译代码,网址为https://latex-cookbook.net/chapter-10

You can find further code examples in Chapter 10, Advanced Mathematics of LaTeX Cookbook with compilable code on that book's website at https://latex-cookbook.net/chapter-10.

编写基本公式

Writing basic formulas

LaTeX 提供三种书写模式:

LaTeX offers three writing modes:

  • 段落模式:文本被排版为单词序列行、段落和页面。那是我们在前几章中使用的内容。
  • Paragraph mode: The text is typeset as a sequence of words in lines, paragraphs, and pages. That's what we used in the previous chapters.
  • 从左到右模式:文本是一系列单词,但是LaTeX 将它从左到右排版而不打断该行。例如,\mbox的参数将在这种模式下排版;所以\mbox防止断字。
  • Left-to-right mode: The text is a sequence of words, but LaTeX typesets it from left to right without breaking the line. For instance, the argument of \mbox will be typeset in this mode; so \mbox prevents hyphenation.
  • 数学模式:在这里,LaTeX 将字母视为数学符号。这就是它们以斜体排版的原因,这是变量的常见做法。许多符号只能在数学模式下使用。这些符号是根、和号、关系号、数学重音符号、箭头和各种定界符,例如方括号和大括号。LaTeX 忽略字母和符号之间的空格字符。相反,间距取决于符号的类型——关系符号的间距不同于开始或结束定界符的间距。所有数学表达式都需要这种模式。
  • Math mode: Here, LaTeX treats letters as math symbols. That's why they're typeset in italics, which is common practice for variables. A lot of symbols can only be used in math mode. Such symbols are roots, sum signs, relation signs, math accents, arrows, and various delimiters, such as brackets and braces. LaTeX ignores space characters between letters and symbols. Instead, the spacing depends on the type of symbols—spacing of relation signs is different from spacing of opening or closing delimiters. All math expressions require this mode.

现在我们将进入数学模式第一次。

Now we shall enter the math mode for the first time.

我们的第一篇数学课本将处理二次方程的解。我们将用常量、变量、平方的上标和解的下标来排版公式。解决方案本身需要一个根符号。最后,我们将使用公式的交叉引用。这是一个相当大的挑战,所以让我们将其分解为以下步骤:

Our first math text shall deal with the solutions of quadratic equations. We will typeset formulas with constants, variables, superscripts for the square, and subscripts for the solutions. The solution itself needs a root symbol. Finally, we will use cross-references to formulas. That's quite a challenge, so let's break it down into the following steps:

  1. 开始一个新文档。现在,我们不需要任何包:

    \文档类{文章}

    \开始{文档}

    \section*{二次方程}

  2. Start a new document. For now, we don't need any packages:

    \documentclass{article}

    \begin{document}

    \section*{Quadratic equations}

  3. 陈述二次方程及其条件。为它使用方程式环境。使用\(\)包围文本中的小块数学:

    二次方程

    \begin{方程式}

      \标签{四边形}

      ax^2 + bx + c = 0,

    \end{方程式}

    其中 \( a, b \) 和 \( c \) 是常数,

    \( a \neq 0 \),变量有两个解

    \( X \):

  4. State the quadratic equation with its conditions. Use an equation environment for it. Surround small pieces of math within text using \( and \):

    The quadratic equation

    \begin{equation}

      \label{quad}

      ax^2 + bx + c = 0,

    \end{equation}

    where \( a, b \) and \( c \) are constants and

    \( a \neq 0 \), has two solutions for the variable

    \( x \):

  5. 使用另一个方程的解决方案。平方根的命令是\sqrt。分数的命令是\frac

    \begin{方程式}

      \标签{根}

      x_{1,2} = \frac{-b \pm \sqrt{b^2-4ac}}{2a}。

    \end{方程式}

  6. Use another equation for the solutions. The command for a square root is \sqrt. The command for a fraction is \frac:

    \begin{equation}

      \label{root}

      x_{1,2} = \frac{-b \pm \sqrt{b^2-4ac}}{2a}.

    \end{equation}

  7. 让我们介绍判别式并讨论案例零。为了获得未编号的显示方程,我们用\[\]包围公式:

    如果 \emph{判别式} \( \Delta \) 与

    \[

      \Delta = b^2 - 4ac

    \]

    为零,则方程 (\ref{quad}) 有双解:

    (\ref{root}) 变成

    \[

      x = - \frac{b}{2a}。

    \]

    \end{文档}

  8. Let's introduce the discriminant and discuss case zero. To get an unnumbered displayed equation, we surround the formula with \[ and \]:

    If the \emph{discriminant} \( \Delta \) with

    \[

      \Delta = b^2 - 4ac

    \]

    is zero, then the equation (\ref{quad}) has a double solution:

    (\ref{root}) becomes

    \[

      x = - \frac{b}{2a}.

    \]

    \end{document}

  9. 单击排版以编译文档。方程式参考未解决第一次运行看起来像(?)。再次编译让 LaTeX解决它们,看看结果:
  10. Click on Typeset to compile the document. The equation references are unresolved in the first run and look like (?). Compile again to let LaTeX resolve them, and look at the result:
图 9.1 – 数学文本的示例

图 9.1 – 数学文本的示例

Figure 9.1 – An example of a mathematical text

正如我们在第 1 章LaTeX 入门中所说,编写公式看起来也很像编程。我们根据命令构建公式;有带参数的命令,例如用于根和分数的命令,以及用于符号的简单命令,例如用于希腊字母的命令。大多数符号必须在数学环境中并且不能在常规文本中使用。然而,本章将帮助您掌握它,而且结果是值得的。

Just as we said in Chapter 1, Getting Started with LaTeX, writing formulas also looks a lot like programming. We build formulas from commands; there are commands with arguments, such as for roots and fractions, and simple commands for symbols, such as for Greek letters. Most symbols have to be within a math environment and don't work within regular text. However, this chapter will help you master it, and the results are worth the effort.

方程式环境创建了一个显示的公式。这个公式已经水平居中,LaTeX 前后加了一些垂直空间。此外,这些公式是连续编号的。

The equation environment created a displayed formula. This formula has been horizontally centered, and LaTeX added some vertical space before and after. Furthermore, these formulas are consecutively numbered.

然而,\[\]\(\)实际上也是环境。让我们在下一节中更仔细地了解更多详细信息。

However, \[\] and \(\) are also, in reality, environments. Let's look more closely for further details in the next sections.

在文本中嵌入数学表达式

Embedding math expressions within text

乳胶提供文本公式的数学环境:

LaTeX provides the math environment for in-text formulas:

\开始{数学}

\begin{math}

  表达

  expression

\结束{数学}

\end{math}

因为它非常努力地为每个小表达式或符号编写这个环境,LaTeX 提供了一个别名,它做同样的事情:

Since it's very trying to write this environment for each small expression or symbol, LaTeX offers an alias, which does the same:

\(

\(

  表达

  expression

\)

\)

您也可以在不换行的情况下编写它,例如\( expression \)

You may also write it without line breaks, such as \( expression \).

第三种方法是使用来自 TeX 的快捷方式:$ expression $

A third way is by using a shortcut, coming from TeX: $ expression $.

后者的缺点是开始和结束数学环境的命令相同,容易出错。然而,它更容易打字,这可能是它仍然受到 LaTeX 用户欢迎的原因。

A disadvantage of the latter is that the commands for beginning and ending the math environment are the same, which may easily lead to errors. However, it's much easier to type, which may be the reason why it's still popular among LaTeX users.

内联编写公式可以节省空间并允许流畅的解释。建议在文本中使用简短的数学表达式。

Writing formulas inline saves space and allows fluent explanations. This is recommended for short math expressions within the text.

显示公式

Displaying formulas

对于显示的公式,必须居中,LaTeX 提供了displaymath环境:

For displayed formulas, which have to be centered, LaTeX offers the displaymath environment:

\begin{显示数学}

\begin{displaymath}

  表达

  expression

\结束{显示数学}

\end{displaymath}

这种环境的效果是,当段落结束时,它后面有一些垂直空间,然后显示居中的公式,然后再次是垂直空间。因为这个数学环境会处理间距,所以不要在它前后留下空行。由于额外的段落分隔符,这会导致额外的垂直空间。

The effect of this environment is that when the paragraph ends, some vertical space follows it, then the centered formula is displayed, which is again followed by the vertical space. As this math environment takes care of the spacing, don't leave empty lines before and after it. This would cause additional vertical space because of the extra paragraph breaks.

还有,对于这个环境,有捷径。在这里,它带有方括号,而不是上一节中的括号:

Also, for this environment, there's a shortcut. Here, it's with square brackets, instead of parentheses as in the previous section:

\[

\[

  表达

  expression

\]

\]

在这种情况下,将\[\]快捷方式放在不同的行上通常可以提高代码的可读性。

In this case, putting the \[ and \] shortcuts on separate lines commonly improves the code readability.

不要使用您可能在其他地方看到的类似$$ 表达式 $$ TeX 低级命令来显示公式,因为这在 LaTeX 中存在问题,例如不正确的垂直间距。

Do not use the similar $$ expression $$ TeX low-level command that you may see elsewhere for displayed formulas, as this has issues with LaTeX, such as incorrect vertical spacing.

显示样式中的公式更加突出——它们居中并且前后有额外的空间。选择最适合文本可读性的样式。

Formulas in the displayed style are more prominent – they are centered and have additional space before and after. Choose the style that is optimal for the readability of your text.

笔记

Note

对于本章的其余部分,所有代码段都将使用数学模式。我们要么明确使用数学环境,要么假设我们已经处于短代码片段的数学模式。

For the rest of this chapter, all pieces of code will use math mode. Either we will explicitly use a math environment or assume that we are already in math mode for short code snippets.

编号方程式

Numbering equations

一般而言,方程式和公式可能被编号。但是,这仅适用于显示的公式。方程式环境对此负责:

Equations and formulas, in general, may be numbered. However, this applies only to displayed formulas. The equation environment is responsible for this:

\begin{方程式}

\begin{equation}

  \标签{键}

  \label{key}

  表达

  expression

\end{方程式}

\end{equation}

它看起来类似于displaymath,但这次是编号的。该数字将显示在等式右侧的括号中,如图9.1所示。

It looks similar to displaymath, but it's numbered this time. The number will be displayed in parentheses on the right side of the equation, as we can see in Figure 9.1.

添加下标和上标

Adding subscripts and superscripts

由于指数和指数是经常使用,有用于排版它们的简明命令。

As exponents and indexes are frequently used, there are concise commands for typesetting them.

下划线_给出索引或下标:

An underscore _ gives an index or subscript:

{表达式}_{下标}

{expression}_{subscript}

插入符号^产生指数或上标:

A caret ^ produces an exponent or superscript:

{表达式}^{上标}

{expression}^{superscript}

正如我们在这里看到的,我们使用大括号来定义表达式的相关部分。

As we see here, we use braces to define the relevant part of the expression.

下标和上标可以嵌套。如果在同一表达式中同时使用下标和上标,则^_的顺序无关紧要。如果是单个字母、数字或符号,您可以省略大括号。让我们看一个例子:

Subscripts and superscripts may be nested. If you use both subscripts and superscripts in the same expression, the order of ^ and _ doesn't matter. In the case of single letters, numerals, or symbols, you can omit the braces. Let's look at an example:

\[ x_1^2 + x_2^2 = 1, \quad 2^{2^x} = 64 \]

\[ x_1^2 + x_2^2 = 1, \quad 2^{2^x} = 64 \]

这给了我们输出:

This gives us the output:

图 9.2 – 下标和上标

图 9.2 – 下标和上标

Figure 9.2 – Subscripts and superscripts

您还可以注意到较高级别的指数小于较低级别的指数。当我们嵌套下标或上标时,内部字体会变小。

You can also notice that the exponent at the higher level is smaller than the exponent at the lower level. When we nest subscripts or superscripts, the inner font size becomes smaller.

使用运算符

Using operators

三角函数,对数函数以及其他解析和代数函数通常用直立的罗马字母书写。简单地输入log看起来像是三个变量的乘积:log。有许多常用功能或所谓的运算符的命令。这是按字母顺序排列的预定义列表:

Trigonometric functions, logarithmic functions, and other analytic and algebraic functions are commonly written with upright Roman letters. Simply typing log would otherwise look like a product of the three variables: l, o, and g. There are commands for many common functions or so-called operators. Here's an alphabetical list of the predefined ones:

\arccos\arcsin\arctan\arg\cos\cosh\cot\coth\scs\deg\det\dim\exp\gcd\hom\inf\ker , \lg , \lim , \liminf , \limsup , \ln , \log , \max , \min , \Pr ,\sec , \sin , \sinh , \sup , \tan , \tanh

\arccos, \arcsin, \arctan, \arg, \cos, \cosh, \cot, \coth, \scs, \deg, \det, \dim, \exp, \gcd, \hom, \inf, \ker, \lg, \lim, \liminf, \limsup, \ln, \log, \max, \min, \Pr, \sec, \sin, \sinh, \sup, \tan, \tanh

我们可以用两种方式编写模函数——对二元关系使用\bmod ,或者对括号中的模表达式使用\pmod{argument} 。

We can write the modulo function in two ways – either by using \bmod for a binary relation or by using \pmod{argument} for a modulo expression in parentheses.

部分运营商支持下标,在运算符下方显示的公式中设置如下:

Some operators support subscripts, which are set in displayed formulas below the operator as follows:

\[ \lim_{n=1, 2, \ldots} a_n \qquad \max_{x<X} x \]

\[ \lim_{n=1, 2, \ldots} a_n \qquad \max_{x<X} x \]

输出如下:

The output is as follows:

图 9.3 – 带下标的运算符

图 9.3 – 带下标的运算符

Figure 9.3 – Operators with subscripts

上标将设置在运算符上方。

Superscripts would be set above the operator.

当在文本中内联使用运算符时,如下所示:

When operators are used inline within text, like this:

在文本中,我们有 \( \lim_{n=1, 2, \ldots} a_n \)

Within text, we have \( \lim_{n=1, 2, \ldots} a_n \)

和 \( \max_{x<X} x \)。

and \( \max_{x<X} x \).

输出不同:

The output is different:

图 9.4 – 下标

图 9.4 – 下标

Figure 9.4 – Subscripts

这是为了避免文本行之间的间距过大。

That's to avoid a wide spacing between text lines.

此外,图 9.30图 9.31显示了运算符的下标和上标的位置和大小。

In addition, Figure 9.30 and Figure 9.31 show the positioning and size of subscripts and superscripts for operators.

扎根

Taking roots

我们的第一个示例代码章,包含一个平方根:\sqrt{value}。由于存在高阶根,此命令接受一个可选的阶数参数。完整的定义如下:

Our first example code in this chapter, contained a square root: \sqrt{value}. As there are higher-order roots, this command accepts an optional argument for the order. The complete definition is as follows:

\sqrt[顺序]{值}

\sqrt[order]{value}

根可以嵌套。我们可以在这个例子中看到它:

Roots may be nested. We can see it in this example:

\sqrt[64]{x} = \sqrt{\sqrt{\sqrt{\sqrt{\sqrt{\sqrt{x}}}}}}

\sqrt[64]{x} = \sqrt{\sqrt{\sqrt{\sqrt{\sqrt{\sqrt{x}}}}}}

输出如下:

The output is as follows:

图 9.5 – 嵌套的根

图 9.5 – 嵌套的根

Figure 9.5 – Nested roots

LaTeX 会根据值表达式的高度和宽度自动调整根符号的大小。这就是为什么外根比内根大的原因。

LaTeX adjusts the size of the root symbol automatically to the height and the width of the value expression. That's why outer roots are bigger than inner roots.

写分数

Writing fractions

文字内公式中,您可以只写/来表示分数,例如\( (a+b)/2 \)。对于较大的分数,有\frac命令:

Within text formulas, you may just write / to denote fractions, such as \( (a+b)/2 \). For larger fractions, there's the \frac command:

\frac{分子}{分母}

\frac{numerator}{denominator}

这是一个例子:

Here is an example:

\[ \frac{n(n+1)}{2} \quad \frac{\frac{\sqrt{x}+1}{2}-x}{y^2} \]

\[ \frac{n(n+1)}{2} \quad \frac{\frac{\sqrt{x}+1}{2}-x}{y^2} \]

输出为如下:

The output is as follows:

图 9.6 – 分数和嵌套分数

图 9.6 – 分数和嵌套分数

Figure 9.6 – Fractions and nested fractions

LaTeX 会自动将分隔线调整为分子和分母的最大宽度。

LaTeX adjusts the separation line automatically to the maximum width of the numerator and denominator.

写希腊字母

Writing Greek letters

数学家喜欢用例如,希腊字母表示常量。要获得小写希腊字母,请为命令写入带有反斜杠的名称。以下是小写希腊字母及其对应的 LaTeX 命令:

Mathematicians like to use Greek letters, for instance, to denote constants. To get a lowercase Greek letter, write the name with a backslash for the command. Here are the lowercase Greek letters with their corresponding LaTeX commands:

图 9.7 – 小写希腊字母

图 9.7 – 小写希腊字母

Figure 9.7 – Lowercase Greek letters

对于某些字母,可以使用变体:

For some letters, variants are available:

图 9.8 – 一些希腊字母的替代变体

图 9.8 – 一些希腊字母的替代变体

Figure 9.8 – Alternative variants for some Greek letters

由于omicron看起来像o,因此没有针对它的命令。它类似于大多数大写希腊字母,就像罗马字母一样。例如,没有\Alpha\Beta;只需键入AB。看起来与罗马字母不同的大写希腊字母生成如下:

As the omicron looks like an o, there's no command for it. It's similar to most uppercase Greek letters, which are like Roman letters. For example, there's no \Alpha or \Beta; just type A or B instead. The uppercase Greek letters, which look different from Roman letters are produced as follows:

图 9.9 – 大写希腊字母

图 9.9 – 大写希腊字母

Figure 9.9 – Uppercase Greek letters

可以看到小写希腊字母是斜体排版,大写希腊字母是直写的。该选择来自数学中的传统写作风格。只有斜体小写字母和有限数量的正体的节俭希腊字母来自 TeX 早期字符表中的空间限制。

You can see that lowercase Greek letters are typeset in italics, and uppercase Greek letters are written upright. That selection comes from the traditional writing style in mathematics. The frugality of having only italic lowercase letters and a limited amount of upright Greek letters comes from space limitations in character tables in the early time of TeX.

如果你想要直立的希腊字母,你可以写\usepackage{upgreek}并使用以下命令:

If you would like to have upright Greek letters, you may write \usepackage{upgreek} and use the following commands:

图 9.10 – 直立的小写希腊字母

图 9.10 – 直立的小写希腊字母

Figure 9.10 – Upright lowercase Greek letters

提供以下变体:

The following variants are available:

图 9.11 – 一些希腊字母的替代直立变体

图 9.11 – 一些希腊字母的替代直立变体

Figure 9.11 – Alternative upright variants for some Greek letters

直立的希腊字母取自 Euler 字体,而不是默认的 Computer Modern 字体。

The upright Greek letters are taken from the Euler font and not from the default Computer Modern fonts.

写脚本字母

Writing script letters

对于26位大写字母 A、B、C、...、Z,有一个书法形状,由\mathcal生成:

For the 26 uppercase letters A, B, C, …, Z, there's a calligraphic shape, produced by \mathcal:

\[ \mathcal{A}, \mathcal{B}, \mathcal{C}, \ldots, \mathcal{Z} \]

\[ \mathcal{A}, \mathcal{B}, \mathcal{C}, \ldots, \mathcal{Z} \]

这是他们的样子:

This is how they look:

图 9.12 – 书法字母

图 9.12 – 书法字母

Figure 9.12 – Calligraphic letters

有套餐提供不同的书法字体,例如zapfinoxits

There are packages offering different calligraphic fonts, such as zapfino and xits.

产生一个省略号

Producing an ellipsis

你已经知道\ldots意味着低省略号。它也适用于数学模式。我们主要在字母和逗号之间使用低省略号。在操作和关系符号之间,写一个居中的省略号是常见的做法。此外,矩阵可能需要对角线或垂直椭圆。以下是我们如何生产它们:

You already know \ldots means a low ellipsis. It also works in math mode. We use the low ellipsis mainly between letters and commas. Between operation and relation symbols, writing a centered ellipsis is common practice. Furthermore, a matrix may require a diagonal or a vertical ellipsis. Here's how we can produce them:

图 9.13 – 不同位置的省略号

图 9.13 – 不同位置的省略号

Figure 9.13 – Ellipsis in various positions

对于另一个方向的对角线省略号,您可以使用\reflectbox{$\ddots$}\reflectbox命令在序言中需要\usepackage{graphicx} 。

For a diagonal ellipsis in the other direction, you can use \reflectbox{$\ddots$}. The \reflectbox command requires \usepackage{graphicx} in your preamble.

更改字体、样式和大小

Changing the font, style, and size

第 2 章格式化文本和创建宏中,我们学习了修改常用文本字体。我们可以用在数学模式下更改字体样式的更多命令:

In Chapter 2, Formatting Text and Creating Macros, we learned to modify the common text font. We can use further commands to change the font style in math mode:

图 9.14 – 数学字体命令

图 9.14 – 数学字体命令

Figure 9.14 – Math font commands

因此,例如,一旦您将\usepackage{dsfont}添加到文档序言中,您就可以使用\mathds{Z}命令来获得双笔画字母 Z。

So, for example, once you added \usepackage{dsfont} to your document preamble, you can use the \mathds{Z} command to get a double-stroke letter Z.

虽然数学模式中的字母是斜体,但它们被视为独立的符号,导致与斜体单词的间距不同。例如,在数学模式中,fi可能是变量fi的乘积,但不是连字fi。比较这两个版本:

Though letters in math mode are italic, they are considered separate as symbols, resulting in a different spacing than an italic word. For instance, in math mode, fi may be the product of the variables f and i but not the ligature fi. Compare these two versions:

\(定义\) 和 \textit{定义}

\(Definition\) and \textit{Definition}

这给了我们以下信息:

This gives us the following:

图 9.15 – 简单的数学书写与斜体文本

图 9.15 – 简单的数学书写与斜体文本

Figure 9.15 – Plain math writing versus italic text

右边的版本肯定更好。

The version on the right is definitely better.

此外,\textit将参数视为斜体数学字体的文本;那不是文字字体。关于公式中的文本,请阅读本章后面的将文本插入公式部分。

Also, \textit treats arguments as text in italic math font; that's not the text font. Regarding text within formulas, please read the Inserting text into formulas section later in this chapter.

如果你想切换到粗体一个完整的数学表达式的字体,你可以在表达式前使用\boldmath声明,即在数学模式之外。\unboldmath声明切换回标准字体。后者也用于数学模式之外。

If you wish to switch to bold typeface for a complete math expression, you can use the \boldmath declaration before the expression, that is, outside math mode. The \unboldmath declaration switches back to the standard typeface. Also the latter is used outside math mode.

要使部分公式变为粗体,您可以使用\mbox命令切换到从左到右的模式,并在其参数中使用\boldmath 。

To make parts of a formula bold, you can switch to left-to-right mode with the \mbox command and use \boldmath in its argument.

有四种数学样式可用,它们决定了排版的种类和字体大小:

Four math styles are available, which determines the kind of typesetting and the font size:

  • \textstyle:字母和符号在文本公式中书写。
  • \textstyle: Letters and symbols are written as within in-text formulas.
  • \displaystyle:字母和符号的书写方式与显示的公式相同。
  • \displaystyle: Letters and symbols are written as they would be in displayed formulas.
  • \scriptstyle:这对下标和上标使用较小的字体大小。
  • \scriptstyle: This uses a smaller font size for subscripts and superscripts.
  • \scriptscriptstyle:这为嵌套脚本样式使用了更小的字体大小。
  • \scriptscriptstyle: This uses a much smaller font size for the nested script style.

\textstyle\displaystyle主要在两个方面不同——对于\textstyle,可变大小的符号更小,下标和上标通常放在表达式旁边,而不是分别放在下面和上面。否则,字体大小相同。

\textstyle differs from \displaystyle in mainly two ways – with \textstyle, variable-sized symbols are smaller, and subscripts and superscripts are usually placed beside the expression instead of below and above, respectively. Otherwise, the font size is the same.

LaTeX 切换风格自动地。如果你写一个简单的指数,它将被排版为字体较小的脚本样式。

LaTeX switches the style automatically. If you write a simple exponent, it will be typeset in script style with smaller font size.

您可以使用此处列出的四个命令之一强制使用所需的样式。因此,例如,您可以将\displaystyle插入公式中,因此即使在文本中,它也会像在显示的公式中一样出现:更大的分数和更大的和符号。此外,下标位于下方,上标位于上方。注意——这会增加行距。

You may force the desired style using one of the four commands listed here. So, for instance, you can insert \displaystyle into a formula, so even within the text, it would appear like in a displayed formula: bigger fraction and bigger sum signs. Furthermore, subscripts are placed below, and superscripts are placed above. Note – this increases the line spacing.

自定义显示的公式

Customizing displayed formulas

两个文档类选项修改公式的显示方式:

Two document class options modify the way the formulas are displayed:

  • fleqn for flush left equations:LaTeX 将在左边距对齐所有显示的公式。
  • fleqn for flush left equations: LaTeX will align all displayed formulas at the left margin.
  • leqno for left equation numbers:所有带编号的公式都会在左侧而不是右侧获得数字。
  • leqno for left equation numbers: All numbered formulas would get the numbers on the left side instead of the right.

通常,公式不会单独显示。我们可能会遇到以下情况:

Often, formulas are not displayed just standalone. We may encounter situations where the following applies:

  • 公式太长,无法放在一行中。
  • A formula is too long to fit on one line.
  • 几个公式逐行列出。
  • Several formulas are listed row by row.
  • 一个方程是要一步步变换的。
  • An equation is to be transformed step by step.
  • 一连串的不平等跨越不止一条线。
  • A chain of inequalities spans over more than one line.
  • 几个公式要在关系符号处对齐。
  • Several formulas are to be aligned at relation symbols.

我们也可能会遇到类似的我们必须编写多行公式的情况,通常需要某种对齐方式。amsmath包为几乎所有此类需求提供了专门的环境,这将是我们的下一个目标t 部分的主题。

We may also encounter similar situations where we have to write multi-line formulas, often with some kind of alignment. The amsmath package offers specialized environments for nearly every such need, which will be our next section's topic.

排版多行公式

Typesetting multi-line formulas

我们将使用amsmath包来排版一个很长的公式和一个方程组:

We shall use the amsmath package to typeset a very long formula and a system of equations:

  1. 在 A6 纸张大小上开始一个新文档以具有更小的文本宽度,这样我们就可以在不输入超长公式的情况下看到换行符会发生什么:

    \文档类{文章}

    \usepackage[a6paper]{几何}

  2. Start a new document on A6 paper size to have a smaller text width, so we can see what happens with line breaks without typing super long formulas:

    \documentclass{article}

    \usepackage[a6paper]{geometry}

  3. 加载amsmath包,并开始文档:

    \usepackage{amsmath}

    \开始{文档}

  4. Load the amsmath package, and begin the document:

    \usepackage{amsmath}

    \begin{document}

  5. 使用多行环境将一个长方程跨越三行。用双反斜杠\\结束行,最后一个除外:

    \begin{多行}

      \sum = a + b + c + d + e \\

               + f + g + h + i + j \\

               + k + l + m + n

    \end{多行}

    \end{文档}

  6. Use the multline environment to span a long equation over three lines. End the lines with a double backslash \\, except the last one:

    \begin{multline}

      \sum = a + b + c + d + e \\

               + f + g + h + i + j \\

               + k + l + m + n

    \end{multline}

    \end{document}

  7. 点击Typeset编译,看公式:
    图 9.16 – 跨越三行的公式

    图 9.16 – 跨越三行的公式

  8. Click on Typeset to compile, and look at the formula:

    Figure 9.16 – A formula spanning three lines

  9. 现在我们处理一个方程组。使用gather环境添加这些方程式。同样,以\\结束行,最后一行除外:

    \开始{聚集}

      x + y + z = 0 \\

          y - z = 1

    \结束{聚集}

  10. Now we handle a system of equations. Use the gather environment to add these equations. Again, end lines with \\ except the last one:

    \begin{gather}

      x + y + z = 0 \\

          y - z = 1

    \end{gather}

  11. 再次编译,然后看方程式:
    图 9.17 – 一个有两个方程的系统

    图 9.17 – 一个有两个方程的系统

  12. Compile again, and look at the equations:

    Figure 9.17 – A system with two equations

  13. 通常,方程系统以等号对齐。我们开工吧。使用符号&标记我们希望对齐的点:

    \开始{对齐}

      x + y + z &= 0 \\

          y - z &= 1

    \结束{对齐}

  14. Commonly, equation systems are aligned at the equal sign. Let's do this. Use the ampersand symbol & to mark the point that we wish to align:

    \begin{align}

      x + y + z &= 0 \\

          y - z &= 1

    \end{align}

  15. 再次编译;现在方程式按需要对齐:
  16. Compile again; now the equations are aligned as desired:
图 9.18 – 具有两个对齐方程的系统

图 9.18 – 具有两个对齐方程的系统

Figure 9.18 – A system with two aligned equations

因为我们加载了amsmath包,所以我们可以访问多个多行数学环境。这种环境中的每一行都以\\结束,最后一行除外。否则,如果我们将\\添加到最后一行,LaTeX 会认为另一行已经开始并且还会对其进行编号,即使如果该行是空的。

Because we loaded the amsmath package, we have access to several multi-line math environments. Each line in such an environment is ended by \\, except the last one. Otherwise, if we add \\ to the last line, LaTeX would think another line has been started and would also number it, even if the line is empty.

对齐方式取决于环境。这是amsmath多行环境的列表:

The alignment depends on the environment. Here's a list of the amsmath multi-line environments:

  • multline:第一行左对齐,最后一行右对齐,所有其他行居中。
  • multline: The first line is left-aligned, the last line is right-aligned, and all others are centered.
  • gather:每行居中。
  • gather: Each line is centered.
  • align:使用&标记要对齐公式的符号。如果您需要多个对齐的列,请使用另一个&来结束一列。
  • align: Use & to mark a symbol where you want to align the formulas. Use another & to end a column if you need several aligned columns.
  • flalign:这类似于与多列对齐,但列分别与左边距和右边距齐平。
  • flalign: This is similar to align with more than one column, but the columns are flush to the left and the right margin, respectively.
  • alignat:这允许在多个位置对齐,每个位置都必须用&标记。
  • alignat: This allows alignment at several places, where each has to be marked by &.
  • split:类似于align,但在另一个数学环境中。
  • split: Similar to align, but within another math environment.
  • alignedgatheredalignedat:用于数学环境中的对齐块。这可以是显示数学或内联数学。
  • aligned, gathered, and alignedat: Used for an aligned block within a math environment. This can either be displayed math or inline math.

可以按如下方式调整编号。

Numbering can be adjusted as follows.

对多行公式中的行进行编号

Numbering rows in multi-line formulas

在多线数学中环境中,每一行都像普通的一样编号方程。如果你想取消一行的编号,在行尾之前写上\notag 。

In multi-line math environments, each line is numbered like an ordinary equation. If you wish to suppress the numbering of a line, write \notag before the end of the line.

如果你想有一个特殊的编号风格,比如一个符号或名称作为一个公式的标签,你可以使用\tag命令,比如\tag{$\star$}用星号来标记它,或\tag{name}将其标记为(name)

If you would like to have a particular style of numbering, such as a symbol or name as a tag for a formula, you can use the \tag command, such as \tag{$\star$} to mark it with a star, or \tag{name} for tagging it as (name).

如果您想完全避免编号,请使用带星号的变体,例如align*gather* 。

Use a starred variant such as align* or gather* if you would like to avoid numbering altogether.

将文本插入公式

Inserting text into formulas

将一些文本插入到公式,标准 LaTeX 提供了\mbox命令。amsmath提供了进一步的控制:

To insert some text into a formula, standard LaTeX provides the \mbox command. amsmath offers further controls:

  • \text{words}插入数学公式中的文本。大小根据当前的数学风格进行调整;\text在下标或上标中生成较小的文本。
  • \text{words} inserts text within a math formula. The size is adjusted according to the current math style; \text produces smaller text within subscripts or superscripts.
  • \intertext{text}暂停公式,然后在单独的段落中打印文本,然后恢复多行公式,保持对齐。将其用于较长的文本。
  • \intertext{text} suspends the formula, then prints the text in a separate paragraph, then the multi-line formula is resumed, keeping the alignment. Use it for longer text.

当您想在数学环境中使用文本时,这些命令非常有用。

These commands are good when you would like to use text within math environments.

现在让我们看看数学符号。

Let's now look into mathematical symbols.

探索丰富的数学符号

Exploring the wealth of math symbols

让我们超越写作变量和基本数学运算符。我们可能需要许多用于特定目的的符号:关系符号、一元和二元运算符、类函数运算符、求和和积分符号以及后者的变体、箭头等等。LaTeX 和附加包提供了数千种用于多种用途的符号。

Let's go beyond writing variables and basic math operators. We may need many symbols for particular purposes: relation signs, unary and binary operators, function-like operators, sum and integral symbols and variants of the latter, arrows, and many more. LaTeX and additional packages offer thousands of symbols for many purposes.

那么,让我们看看一些数学符号和生成它们的命令。我们将涵盖许多标准的 LaTeX 符号;latexsym包提供了一些额外符号。使用例如amssymb包可以访问更多符号。

So, let's look at some math symbols and the commands for producing them. We shall cover many standard LaTeX symbols; the latexsym package provides some additional symbols. Even more symbols are accessible using, for instance, the amssymb package.

二元运算符号

Binary operation symbols

除了加上和减号,还有一些操作:

Besides plus and minus, there are a few more operations:

图 9.19 – 二元运算符号

图 9.19 – 二元运算符号

Figure 9.19 – Binary operation symbols

您需要在文档序言中包含\usepackage{latexsym}才能在这里使用最后一行中的符号。

You need to have \usepackage{latexsym} in your document preamble to be able to use the symbols in the last row here.

二元关系符号

Binary relation symbols

表达式的值可能是相等,在这种情况下你只需要一个等号=,但还有其他可能的关系。例如,它们可能是全等的、平行的,或者它们可能具有任何其他关系:

Values of expressions might be equal, in which case you just need an equal sign =, but there are other possible relations. For example, they may be congruent, parallel, or they might have any other relation:

图 9.20 – 二元关系符号

图 9.20 – 二元关系符号

Figure 9.20 – Binary relation symbols

你可以否定任何关系通过在它之前插入\not。所以,对于not equivalent,使用\not \equiv来创建 acrossed-out \equiv符号。

You can negate any relation by inserting \not before it. So, for not equivalent, use \not \equiv to create a crossed-out \equiv symbol.

不等式关系符号

Inequality relation symbols

如果表达式不相等,我们可以用不同的方式描述不平等:

If expressions are not equal, we can describe the inequality in different ways:

图 9.21 – 不等式关系符号

图 9.21 – 不等式关系符号

Figure 9.21 – Inequality relation symbols

在这里,\neq看起来与您在上一节中编写\not=时得到的完全一样。

Here, \neq looks precisely like what you get when you write \not=, as in the previous section.

子集和超集符号

Subset and superset symbols

用于比较集合和表达关系它们之间,有很多符号:

For comparing sets and expressing relations between them, there are many symbols:

图 9.22 – 子集和超集符号

图 9.22 – 子集和超集符号

Figure 9.22 – Subset and superset symbols

还有,你这可以用\not来否定这样的集合关系。

Also, here you can use \not to negate such a set relation.

箭头

Arrows

LaTeX 为我们提供了许多不同的箭头:

LaTeX provides us with lots of different arrows:

图 9.23 – 箭头

图 9.23 – 箭头

Figure 9.23 – Arrows

箭头用于暗示、映射或描述性表达。

Arrows are used for implications, maps, or descriptive expressions.

鱼叉

Harpoons

有特殊的称为鱼叉的箭头:

There are special arrows called harpoons:

图 9.24 – 鱼叉

图 9.24 – 鱼叉

Figure 9.24 – Harpoons

鱼叉是使用,例如,我n 化学反应式。

Harpoons are used, for example, in chemical reaction formulas.

源自字母的符号

Symbols derived from letters

一些类似字母的符号用于数学:

Some letter-like symbols are used in math:

图 9.25 – 从字母派生的符号

图 9.25 – 从字母派生的符号

Figure 9.25 – Symbols derived from letters

数学家可能经常在语句中使用\in\forall\exists

Mathematicians will probably often use \in, \forall, and \exists in statements.

杂项符号

Miscellaneous symbols

这里有更多的 LaTeX 符号不符合上述类别:

Here are more LaTeX symbols that do not match the aforementioned categories:

图 9.26 – 额外的 LaTeX 符号

图 9.26 – 额外的 LaTeX 符号

Figure 9.26 – Additional LaTeX symbols

综合 LaTeX 符号列表列出了大约 15,000 个分类的符号。如果你需要搜索一个符号,看看这个文档。与往常一样,使用 TeX Live,您可以在命令提示符下使用以下代码打开此文档:

The Comprehensive LaTeX Symbol List lists about 15,000 symbols sorted into categories. If you need to search for a symbol, have a look at this document. As usual, with TeX Live, you could open this document by using the following code at the command prompt:

texdoc 符号

texdoc symbols

或访问https://texdoc.org/pkg/symbols阅读该符号列表。

Or visit https://texdoc.org/pkg/symbols to read that list of symbols.

手写符号识别是一种不同而迷人的方法。您用鼠标(或用手指在触摸屏上)绘制一个符号,软件会尝试识别该符号并告诉您它的代码。让我们快速浏览一下:

Handwritten symbol recognition is a different and fascinating approach. You draw a symbol with the mouse (or with your finger on a touchscreen), and the software tries to recognize the symbol and tells you the code for it. Let's have a quick look:

  1. 访问https://detexify.kirelabs.org
  2. Visit https://detexify.kirelabs.org.
  3. 画进白框。如果它是一个摇摇欲坠的鼠标草图并不重要,就像这样:
    图 9.27 – 手写符号

    图 9.27 – 手写符号

  4. Draw into the white box. It doesn't matter if it's a shaky mouse sketch, like this:

    Figure 9.27 – Handwritten symbol

  5. 几秒钟后,你获取符号和相应代码的建议:
  6. After a few seconds, you get suggestions for symbols and the corresponding code:
图 9.28 – 符号和代码建议

图 9.28 – 符号和代码建议

Figure 9.28 – Symbol and code suggestions

脱毛还提供了一个名字搜索功能。单击顶部的符号按钮,在过滤器中输入一个短语,Detexify 将显示与该短语匹配的符号和命令。

Detexify also offers a name search feature. Click the symbols button at the top, enter a phrase into a filter, and Detexify will show symbols and commands that match that phrase.

写作单位

Writing units

如果你使用文本中的单位,它们不应看起来像变量。例如,米的m不应看起来完全像变量m。同样,s可能代表秒,但不代表变量s。印刷约定是使用直立字体表示单位,而变量则以斜体书写。此外,通常在值和维度之间使用一个窄间距。因此,对于 10 米,您可以编写10\,\mathrm{m}。然而,这是非常耗时的。这就是开发siunitx包的原因,它支持正确和一致的单位排版。它需要阅读一些文档在你可以使用它之前,但这是值得的。在命令提示符处运行texdoc siunitx或访问https://texdoc.org/pkg/siunitx

If you use units in text, they should not look like variables. For example, m for meters should not look exactly like a variable m. Similarly, s may stand for seconds, but not for a variable s. A typographical convention is to use an upright font shape for units, while variables are written in italics. Furthermore, it's common to use a thin space between the value and the dimension. So, for 10 meters, you may write 10\,\mathrm{m}. However, this is very time-consuming. That's why the siunitx package has been developed, which supports correct and consistent typesetting of units. It requires reading some documentation before you can use it, but it's worth the effort. Run texdoc siunitx at the command prompt or visit https://texdoc.org/pkg/siunitx.

可变大小运算符

Variable sized operators

对于求和、乘积和集合运算,我们可以使用大小可变的运算符符号:它们更大显示样式和较小的文本样式。

For sums, products, and set operations, we can use operator symbols that are variable in size: they are bigger in display style and smaller in text style.

图 9.29 – 可变大小的运算符

图 9.29 – 可变大小的运算符

Figure 9.29 – Variable sized operators

让我们看看这在文本样式中意味着什么:

Let's see what this means in text style:

\(

\(

  \int_a^b \! f(x) \, dx = \lim_{\Delta x \rightarrow 0}

  \int_a^b \! f(x) \, dx = \lim_{\Delta x \rightarrow 0}

  \sum_{i=1}^{n} f(x_i) \,\Delta x_i

  \sum_{i=1}^{n} f(x_i) \,\Delta x_i

\)

\)

此代码为我们提供了以下内容:

This code gives us the following:

图 9.30 – 内联文本样式等式

图 9.30 – 内联文本样式等式

Figure 9.30 – Inline text style equation

这是显示样式中的相同方程式:

And this is the same equation in displayed style:

\[

\[

  \int_a^b \! f(x) \, dx = \lim_{\Delta x \rightarrow 0}

  \int_a^b \! f(x) \, dx = \lim_{\Delta x \rightarrow 0}

  \sum_{i=1}^{n} f(x_i) \,\Delta x_i

  \sum_{i=1}^{n} f(x_i) \,\Delta x_i

\]

\]

这次我们得到以下信息:

This time we get the following:

图片 9.31 – 显示的样式方程

图片 9.31 – 显示的样式方程

Figure 9.31 – Displayed style equation

正如我们所见,符号在显示样式中明显更大。

As we see, the symbols are significantly bigger in displayed style.

可变大小的分隔符

Variable sized delimiters

分隔符如圆括号、方括号和花括号的大小可以不同。以下是此类 LaTeX 分隔符:

Delimiters such as parentheses, brackets, and braces can vary in size. The following are such LaTeX delimiters:

图 9.32 – 可变大小的分隔符

图 9.32 – 可变大小的分隔符

Figure 9.32 – Variable sized delimiters

如果在这样的定界符前写\left\right ,它的大小将自动匹配到内部表达式的大小。我们必须成对使用这些尺寸宏。要匹配一对,如果您不希望有第二个分隔符,请使用\left。\对。得到一个看不见的分隔符在一侧。

If you write \left or \right before such a delimiter, its size will be automatically matched to the size of the inner expression. We have to use these size macros in pairs. To match a pair, if you don't wish to have a second delimiter, use \left. or \right. to get an invisible delimiter on one side.

自动自调整定界符对于更大的组合数学术语很有用,例如矩阵,所以让我们接下来研究一下。

Automatically self-adjusting delimiters are useful for bigger composed math terms, such as matrices, so let's look into this next.

建立数学结构

Building math structures

变量和常量很简单。但是还有更复杂的对象,例如二项式系数、向量和矩阵。我们将弄清楚如何排版此类结构。

Variables and constants are simple. But there are more complex objects, such as binomial coefficients, vectors, and matrices. We shall figure out how to typeset such structures.

让我们从简单的数组开始。

Let's begin with simple arrays.

创建数组

Creating arrays

用于安排数学周围表达式中的表达式,即数组环境。我们完全像使用表格环境一样使用它。但是,它需要数学模式,并且它的所有条目也是使用数学模式创建的。

For arranging math expressions within a surrounding expression, there's the array environment. We use it exactly like a tabular environment. However, it requires math mode, and all of its entries are made using math mode as well.

例如,我们可以在数组周围使用可变大小的括号:

For example, we can use variable-sized parentheses around an array:

\[

\[

  A = \左(

  A = \left(

    \begin{数组}{cc}

    \begin{array}{cc}

      a_{11} & a_{12} \\

      a_{11} & a_{12} \\

      a_{21} & a_{22}

      a_{21} & a_{22}

    \end{数组}

    \end{array}

  \正确的)

  \right)

\]

\]

这会产生一个矩阵:

This produces a matrix:

图片 9.33 – 一个简单的数组

图片 9.33 – 一个简单的数组

Figure 9.33 – A simple array

有针对矩阵的特定命令。

There are specific commands for matrices.

排版矩阵

Typesetting matrices

amsmath包_为我们提供了许多特殊的矩阵环境。标准矩阵可以由pmatrix环境排版:

The amsmath package provides us with many special matrix environments. A standard matrix can be typeset by the pmatrix environment:

\文档类{文章}

\documentclass{article}

\usepackage{amsmath}

\usepackage{amsmath}

\开始{文档}

\begin{document}

\[

\[

  A = \begin{p矩阵}

  A = \begin{pmatrix}

    a_{11} & a_{12} \\

    a_{11} & a_{12} \\

    a_{21} & a_{22}

    a_{21} & a_{22}

  \结束{p矩阵}

  \end{pmatrix}

\]

\]

\end{文档}

\end{document}

以下是输出:

The following is the output:

图片 9.34 – 一个简单的矩阵

图片 9.34 – 一个简单的矩阵

Figure 9.34 – A simple matrix

您可能会注意到,与上一节中的数组示例相比,括号更靠近矩阵条目。更紧凑的布局来自amsmath风格。

You may notice that the parentheses are closer to the matrix entries than in the array example in the previous section. That tighter layout comes from the amsmath style.

这些是amsmath矩阵环境及其分隔符:

These are amsmath matrix environments and their delimiters:

  • 矩阵:无分隔符
  • matrix: no delimiters
  • pmatrix : 括号 ( )
  • pmatrix: parentheses ( )
  • bmatrix:方括号[]
  • bmatrix: square brackets [ ]
  • B矩阵:大括号{}
  • Bmatrix: braces { }
  • 虚拟矩阵:| |
  • vmatrix: | |
  • 虚拟矩阵:|| ||
  • Vmatrix: || ||
  • smallmatrix:无分隔符——可以根据需要添加,更紧凑
  • smallmatrix: no delimiters – can be added if needed, more compact

紧凑的smallmatrix环境对于常规文本中的矩阵很有用。

The compact smallmatrix environment is useful for matrices within regular text.

写二项式系数

Writing binomial coefficients

我们可以写使用数组和定界符的二项式系数和矩阵。但是,amsmath包提供了更短的命令,例如,用于二项式系数的\binom :

We could write binomial coefficients and matrices using an array together with delimiters. However, the amsmath package provides shorter commands, for instance, \binom for binomial coefficients:

\binom{n}{k} = \frac{n!}{k!(nk)!}

\binom{n}{k} = \frac{n!}{k!(n-k)!}

结果如下:

The result is as follows:

图 9.35 – 方程中的二项式系数

图 9.35 – 方程中的二项式系数

Figure 9.35 – A binomial coefficient in an equation

与数组或矩阵相比,这种小表达式的语法更直接。

That's a more straightforward syntax for such small expressions compared to arrays or matrices.

下划线和上划线

Underlining and overlining

\overline放一条线在其论点之上:

\overline puts a line above its argument:

\overline{\Omega}

\overline{\Omega}

这给了我们以下信息:

This gives us the following:

图片 9.36 – 带上划线的 omega 符号

图片 9.36 – 带上划线的 omega 符号

Figure 9.36 – An overlined omega symbol

对应的是\underline

The counterpart is \underline.

它不一定总是一条线;牙套也很受欢迎。使用大括号的命令是\underbrace\overbrace

It doesn't always have to be a line; braces are popular too. The commands for using braces are \underbrace and \overbrace.

N = \underbrace{1 + 1 + \cdots + 1}_n

N = \underbrace{1 + 1 + \cdots + 1}_n

这导致以下结果:

This results in the following:

图片 9.37 – 表达式下方的大括号

图片 9.37 – 表达式下方的大括号

Figure 9.37 – An underbrace below an expression

下大括号的下标写在下面,上大括号的上标写在上面。

A subscript to an underbrace is written below, a superscript to an overbrace is placed above.

设置口音

Setting accents

第 2 章格式化文本和创建宏中,我们已经了解了如何在文本模式下书写重音符号。为了数学模式,我们需要不同的命令。我们可以将它们应用于任何字母。以下是使用小写字母a作为示例的数学重音列表:

In Chapter 2, Formatting Text and Creating Macros, we've already seen how to write accents in text mode. For math mode, we need different commands. We can apply them to any letter. Here's the list of math accents using the lowercase letter a as an example:

图 9.38 – 各种数学口音

图 9.38 – 各种数学口音

Figure 9.38 – Various math accents

可扩展的口音是宽口音。他们适合他们论点的宽度。

The extensible accents are also called wide accents. They fit the width of their argument.

将一个符号放在另一个符号的上方或下方

Putting a symbol above or below another one

除了阵列环境,还有是直接堆叠表达式的amsmath命令:

Besides the array environment, there are amsmath commands to stack expressions directly:

  • \underset{expression below}{expression}将一个表达式放在另一个表达式下面,使用下面的下标大小。
  • \underset{expression below}{expression} puts an expression below another, using the subscript size below.
  • \overset{expression above}{expression}将一个表达式放在另一个表达式之上,使用上面的下标大小。
  • \overset{expression above}{expression} puts an expression above another, using the subscript size above.

这是我们如何使用这些命令的示例:

This is an example of how we can use these commands:

\underset{\circ}{\cap} \neq \overset{\circ}{\cup}

\underset{\circ}{\cap} \neq \overset{\circ}{\cup}

前面的代码为我们提供了以下内容:

The preceding code gives us the following:

图 9.39 – 将一个符号放在另一个符号的上方或下方

图 9.39 – 将一个符号放在另一个符号的上方或下方

Figure 9.39 – Putting a symbol above or below another one

另一个方便的命令是\stackrel{expression above}{relation}。参见以下公式,例如:

Another handy command is \stackrel{expression above}{relation}. See the following formula, for example:

X \stackrel{\text{def}}{=} 0

X \stackrel{\text{def}}{=} 0

它为我们提供了以下内容:

It gives us the following:

图片 9.40 – 关系符号上方的文本

图片 9.40 – 关系符号上方的文本

Figure 9.40 – Text above a relation symbol

\stackrel将表达式置于关系符号之上。

\stackrel puts an expression above a relation sign.

编写定理和定义

Writing theorems and definitions

LaTeX 提供环境定理、定义等。回到我们的最初在本章的例子中,我们可以使用\newtheorem命令来定义一个Theorem环境thm,如下所示:

LaTeX provides environments for theorems, definitions, and the like. Returning to our very first example in this chapter, we could use the \newtheorem command to define a Theorem environment thm as follows:

\newtheorem{thm}{定理}

\newtheorem{thm}{Theorem}

然后,我们可以声明一个定义环境。我们在这里称它为dfn

Then, we can declare a Definition environment. Let's call it dfn here:

\newtheorem{dfn}[thm]{定义}

\newtheorem{dfn}[thm]{Definition}

我们可以使用引用现有环境的可选参数(此处为thm)。然后这个新环境使用与现有环境相同的计数器。在我们这里的例子中,这意味着在定理 1之后遵循定义 2

We can use an optional argument referring to an existing environment (here, thm). Then this new environment uses the same counter as that already existing environment. In our case here, this means that after Theorem 1 follows Definition 2.

我们可以以这种简单的方式使用这些环境,如下所示:

We can use these environments in this simple way as follows:

\开始{dfn}

\begin{dfn}

  二次方程是以下形式的方程

  A quadratic equation is an equation of the form

  \begin{方程式}

  \begin{equation}

    \标签{四边形}

    \label{quad}

    ax^2 + bx + c = 0,

    ax^2 + bx + c = 0,

  \end{方程式}

  \end{equation}

  其中 \( a, b \) 和 \( c \) 是常量和 \( a \neq 0 \)。

  where \( a, b \) and \( c \) are constants and \( a \neq 0 \).

\结束{dfn}

\end{dfn}

\开始{thm}

\begin{thm}

  二次方程 (\ref{quad}) 有两个解

  A quadratic equation (\ref{quad}) has two solutions for the

  变量 \( x \):

  Variable \( x \):

  \begin{方程式}

  \begin{equation}

    \标签{根}

    \label{root}

    x_{1,2} = \frac{-b \pm \sqrt{b^2-4ac}}{2a}。

    x_{1,2} = \frac{-b \pm \sqrt{b^2-4ac}}{2a}.

  \end{方程式}

  \end{equation}

\结束{thm}

\end{thm}

看一下输出:

Take a look at the output:

图 9.41 – 一个定义和一个定理

图 9.41 – 一个定义和一个定理

Figure 9.41 – A definition and a theorem

在输出中,这些环境被编号并分别标记为DefinitionTheorem。在第 11 章开发大型文档中,当我们准备大型文档时,我们将使用它来创建包含定义、定理和引理的完整文档。

In the output, such environments are numbered and labeled Definition and Theorem, respectively. In Chapter 11, Developing Large Documents, when we prepare large documents, we will use this to create a complete document containing definitions, theorems, and lemmas.

有两个特殊的软件包提供了更大的灵活性:

There are two special packages offering much more flexibility:

  • amsthm提供多种风格,允许精细定制,并包括一个证明环境。
  • amsthm provides several styles, allows fine customization, and includes a proof environment.
  • 定理确实类似的工作,但以更好的方式处理传统的quod erat demonstrandum要显示的内容)证明的结束标记。
  • ntheorem does similar work but handles traditional quod erat demonstrandum (what was to be shown) end marks for proofs in a better way.

如果您想使用这样的环境,请查看他们的文档并比较相关功能以确定哪个包最适合您。像往常一样,在命令提示符下执行texdoc amsthmtexdoc ntheorem ,或访问https://texdoc.org/pkg/amsthmhttps://texdoc.org/pkg/ntheorem

If you would like to use such environments, look at their documentation and compare the relevant features to decide which package is the best for you. As usual, execute texdoc amsthm and texdoc ntheorem at the command prompt, or visit https://texdoc.org/pkg/amsthm and https://texdoc.org/pkg/ntheorem.

选择那些密切相关的软件包之一;不要同时加载。

Choose one of those closely related packages; don't load both.

编写数学的更多工具

Further tools for writing mathematics

通过在命令行输入texdoc amsmath或访问https://texdoc.org/pkg/amsmath来查看amsmath中的所有数学排版选项。

Take a look at all the mathematics typesetting options in amsmath by entering texdoc amsmath at the command line or visit https://texdoc.org/pkg/amsmath.

数学工具包扩展amsmath如果您需要某个特定功能但在标准 LaTeX 和amsmath中都找不到,请查看mathtools。以下是它的一些特点:

The mathtools package extends amsmath. If you need a particular feature and cannot find it, neither in standard LaTeX nor in amsmath, look at mathtools. Here are some of its features:

  • 微调数学排版的工具,例如更紧凑的上标样式
  • Tools for fine-tuning math typesetting, for example, more compact superscript styles
  • 垂直对齐连续运算符的限制
  • Aligning limits of consecutive operators vertically
  • 调整运算符的宽度
  • Adjusting the width of operators
  • 更好地控制标签——修改它们的外观并只显示已引用方程式的标签
  • Better control over tags – modifying their appearance and only showing tags for equations that have been referenced
  • 可扩展符号——更多箭头以及自动调整宽度的能力;还提供可扩展的方括号和花括号以设置在表达式下方或上方
  • Extensible symbols – more arrows along with the ability to adjust their width automatically; also offers extensible brackets and braces to be set under or over expressions
  • 更灵活的矩阵、案例、改进的多行公式和对齐公式之间的箭头的新数学环境
  • New math environments for more flexible matrices, cases, improved multi-line formulas, and arrows between aligned formulas
  • 更短的互文间距更小
  • Less spacing for shorter intertext
  • 成对定界符的声明
  • Declaration of paired delimiters
  • 其他符号,例如垂直居中的冒号,以及关系符号与冒号的组合以及自动调整大小的括号的快捷方式
  • Additional symbols such as a vertically centered colon, along with combinations of relation symbols with colons and shortcuts for auto-sized parentheses
  • 诸如在多行公式中展开行、设置左下标和上标、在斜体文本中排版数学以及生成多行分数等技术
  • Techniques such as spreading lines in multi-line formulas, setting left subscripts and superscripts, typesetting math within italicized text, and producing multi-line fractions

查看这个有价值的包的文档,找出可以应用哪些命令来实现此处列出的样式和对齐方式。通过在命令提示符下运行texdoc mathtools或转到https://texdoc.org/pkg/mathtools打开它。

Have a look at the documentation of this valuable package and find out which commands can be applied to achieve the styles and alignments listed here. Open it by running texdoc mathtools at the command prompt or go to https://texdoc.org/pkg/mathtools.

LaTeX Cookbook 的第 10 章高级数学中,您可以找到许多示例来展示mathtools包的增强功能。访问https://latex-cookbook.net/tag/mathematics/在线查看和运行示例,包括微调数学公式、自动换行方程、绘制函数以及绘制图表和几何图片。

In Chapter 10, Advanced Mathematics, in the LaTeX Cookbook, you can find a lot of examples showing enhancements with the mathtools package. Visit https://latex-cookbook.net/tag/mathematics/ to see and run examples online that include fine-tuning math formulas, automatic line breaking in equations, plotting functions, and drawing diagrams and geometry pictures.

概括

Summary

现在我们可以写出复杂的数学公式,而且我们已经有了编写科学文本的必要工具。我们使用amsmath包,它为我们提供了许多为传统数学排版量身定制的功能。

Now we can write complex math formulas, and we've got the necessary tools to write scientific texts. We worked with the amsmath package, which provides us with many features tailored to traditional mathematical typesetting.

我们现在可以微调数学表达式、对齐和编号方程式,并使用符号字体中的各种数学符号。在下一章中,我们还将使用一般的字体。

We can now fine-tune math expressions, align and number equations, and use various math symbols from symbol fonts. In the next chapter, we will also work with fonts, in general.

第 10 章:使用字体

Chapter 10: Using Fonts

文本的基本字体显着决定了文本的外观。您可以为长篇文章选择特别清晰易读的字体,或者为贺卡选择精美的书法字体。您的求职信可能会使用非常清晰和严肃的字体,而数学文章则需要包含大量符号的字体和与之相匹配的文本字体。

The text's base font determines the appearance of your text significantly. You may choose a font that's especially clear and readable for a long piece of writing or a fancy calligraphic font for a greeting card. Your job application letter might use a very clear and serious font, whereas a mathematical article requires fonts with a lot of symbols and a text font that fits well with them.

到目前为止,我们一直在介绍字体的逻辑属性。尽管我们一直使用 LaTeX 标准字体,但我们从 roman 字体切换到 sans-serif 字体或打字字体,并在第 2 章格式化文本和创建宏中学习了如何将文本设为粗体、斜体或倾斜。但是,我们从未偏离标准字体集。

Until now, we have been covering the logical properties of fonts. Although we have always used the LaTeX standard font, we switched, for instance, from roman to sans-serif, or typewriter, and learned how to make text bold, italicized, or slanted in Chapter 2, Formatting Text and Creating Macros. However, we never deviated from the standard set of fonts.

在本章中,我们将讨论以下主题:

In this chapter, we will cover the following topics:

  • 使用全面的字体包
  • Using comprehensive font bundles
  • 使用特定的字体系列
  • Using specific font families
  • 使用任意字体
  • Using arbitrary fonts

在检查文本外观的同时,我们还将在字体支持数学符号时查看数学公式的设计。

While we will inspect the text appearance, we will also look at the design of math formulas when fonts support math symbols.

由于本书是印刷版和电子版,带有位图图像,因此您不会在本章的字体示例中看到原始的 LaTeX 质量。访问https://latexguide.org/chapter-10查看原始 LaTeX 和 PDF 质量的字体。我们将看到更大尺寸的字体示例,以轻松突出细节和差异。

As this book is printed and electronically distributed with bitmap images, you will not see the original LaTeX quality in the font samples in this chapter. Visit https://latexguide.org/chapter-10 to see the fonts in original LaTeX and PDF quality. We will see the font examples in a larger size to easily highlight the fine details and differences.

让我们从一个例子开始。这将是我们在本章中使用字体的基础。

Let's start with an example. This will be the basis of our work with fonts throughout this chapter.

技术要求

Technical requirements

您可以使用本地 LaTeX 安装,也可以在https://latexguide.org/chapter-10在线编译示例代码。

You can use a local LaTeX installation, or you can compile the example code online at https://latexguide.org/chapter-10.

代码在 GitHub 上可用: https: //github.com/PacktPublishing/LaTeX-Beginner-s-Guide-2nd-Edition-/tree/main/Chapter_10_-_Using_Fonts

The code is available on GitHub: https://github.com/PacktPublishing/LaTeX-Beginner-s-Guide-2nd-Edition-/tree/main/Chapter_10_-_Using_Fonts.

在本章中,我们将使用以下包:arevberamonobookmancalligrachartercmbrightconcmathconcretecourierfontencfouriernchelvetinconsolatakerkiskmathkpfontskurierlmodernmathdesignmiama , newcent , newpx , newpxmathnewtxnewtxmathsfmathunicode-math

In this chapter, we will use the following packages: arev, beramono, bookman, calligra, charter, cmbright, concmath, concrete, courier, fontenc, fouriernc, helvet, inconsolata, kerkis, kmath, kpfonts, kurier, lmodern, mathdesign, miama, newcent, newpx, newpxmath, newtx, newtxmath, sfmath, and unicode-math.

此外,我们将简要讨论这些包:cm-superinputencsansmath

In addition, we will briefly discuss these packages: cm-super, inputenc, and sansmath.

您可以在LaTeX Cookbook第 3 章调整字体中找到其他高级代码示例,并在本书的网站上找到可编译代码: https: //latex-cookbook.net/chapter-3

You can find other and advanced code examples in the LaTeX Cookbook, Chapter 3, Adjusting Fonts, with compilable code at the book's website: https://latex-cookbook.net/chapter-3.

使用全面的字体包

Using comprehensive font bundles

我们从最广泛的字体包开始。去测试字体,我们可以使用pangram。这个词具有希腊血统:pan gramma表示每个字母。它代表一个使用字母表中每个字母的句子。因此,pangram 非常便于显示字体。

We start with the most extensive font bundles. To test fonts, we may use a pangram. This word has a Greek origin: pan gramma means every letter. It stands for a sentence that uses every letter of the alphabet. Thus, a pangram is very convenient for displaying fonts.

我们会打印出来一个非常著名的 pangram 短语,使用拉丁现代字体系列。Latin Modern 与名为Computer Modern 的默认 LaTeX 字体非常相似。然而,拉丁现代包含了很多额外的字符,其中大部分是重音字符。由于这一优势及其非常高的质量,我们可以将其视为标准字体的继承者。让我们看看它在各种字体系列和形状中的外观,以及一个数学公式:

We will print out a very famous pangram phrase using the Latin Modern font family. Latin Modern is very similar to the default LaTeX font called Computer Modern. However, Latin Modern contains a lot of additional characters, most of them being accented characters. Because of this advantage and its very high quality, we can consider it as the successor to the standard font. Let's see how it looks in various font families and shapes, and with a math formula:

  1. 开始一个新文档:

    \文档类{文章}

  2. Start a new document:

    \documentclass{article}

  3. 用额外的数字为 pangram 创建一个宏。它将有一个参数,即我们的字体系列或形状选择命令。我们将在末尾添加一个段落分隔符,如图所示:

    \newcommand{\pangram}[1]{{#1 敏捷的棕色狐狸

    跳过懒狗。1234567890\par}}

  4. Create a macro for the pangram with additional numerals. It will have one argument, which will be our font family or shape selection command. We will add a paragraph break at the end, as shown:

    \newcommand{\pangram}[1]{{#1 The quick brown fox

    jumps over the lazy dog. 1234567890\par}}

  5. 加载fontenc包并选择T1字体编码:

    \usepackage[T1]{fontenc}

  6. Load the fontenc package and choose T1 font encoding:

    \usepackage[T1]{fontenc}

  7. 加载lmodern包以获取 Latin Modern 字体:

    \usepackage{lmodern}

  8. Load the lmodern package to get the Latin Modern font:

    \usepackage{lmodern}

  9. 开始文档并选择字体,以便我们可以清楚地看到细节:

    \开始{文档}

    \大的

  10. Begin the document and choose a large font size so that we can see the details clearly:

    \begin{document}

    \large

  11. 现在我们使用不同的字体设置多次使用我们的\pangram宏:

    \pangram{\rmfamily}

    \pangram{\sffamily}

    \pangram{\ttfamily}

    \pangram{\itshape}

    \pangram{\slshape}

  12. Now we use our \pangram macro several times with different font settings:

    \pangram{\rmfamily}

    \pangram{\sffamily}

    \pangram{\ttfamily}

    \pangram{\itshape}

    \pangram{\slshape}

  13. 为了获得数学字体示例,我们使用在第 9 章编写数学公式”中为图 9.29编写的代码:

    \[

      \int_a^b \! f(x) \, dx = \lim_{\Delta x \rightarrow 0}

      \sum_{i=1}^{n} f(x_i) \,\Delta x_i

    \]

    \end{文档}

  14. To get a math font example, we use the code that we wrote for Figure 9.29 in Chapter 9, Writing Math Formulas:

    \[

      \int_a^b \! f(x) \, dx = \lim_{\Delta x \rightarrow 0}

      \sum_{i=1}^{n} f(x_i) \,\Delta x_i

    \]

    \end{document}

  15. 点击Typeset编译,然后看字体例子:
  16. Click on Typeset to compile, and then look at the font examples:
图 10.1 – 拉丁现代字体示例

图 10.1 – 拉丁现代字体示例

Figure 10.1 – Latin Modern font examples

在我们的\pangram宏中,我们有另一对大括号。在我们的论点{{}}中,外部卷曲大括号包含\newcommand的参数,内部花括号包含我们的命令以限制字体命令的效果。

In our \pangram macro, we had another pair of curly braces. In our argument {{}}, the outer curly brace contains the argument to \newcommand, and the inner curly braces embrace our commands to restrict the effect of the font command.

笔记

Note

\pangram宏对我们来说只是一个小的演示宏,因此我们不必为每个字体系列重复演示语句。在您的日常文档中,加载字体包并编写您的文本。如果需要,您可以在字体系列之间切换,例如\sffamily\ttfamily\rmfamily

The \pangram macro is just a small demonstration macro for us, so we won't have to repeat the demo sentence for each font family. In your everyday documents, load the font package and just write your text. If needed, you can switch between font families such as \sffamily, \ttfamily, or \rmfamily.

第 3 步中,我们选择了一种字体编码。从技术上讲,编码是字符代码到符号的映射的字体。对于西欧语言和英语,强烈推荐使用T1字体编码。它也被称为Cork 编码,因为它是在 TeX 用户组会议期间在爱尔兰科克市开发。默认的 LaTeX 字体编码称为OT1。与OT1相比,T1编码具有更大的编码表,可显着改善重音字符的内部处理。

In step 3, we chose a font encoding. Technically, encodings are mappings of character codes to symbols of the font. For Western European languages and English, the T1 font encoding is highly recommendable. It's also known as Cork encoding because it was developed in the city of Cork in Ireland during a TeX user group conference. The default LaTeX font encoding is called OT1. Compared to OT1, the T1 encoding has larger encoding tables that significantly improve accented characters' internal handling.

例如,使用默认的历史 LaTeX 编码,重音字符 ö 由字形 o 和点组成,将打印在 PDF 文件中。对于T1,ö 是当前字体的单个字形。因此,LaTeX 也可以正确地将断字规则应用于包含重音字符的单词。PDF 阅读器的搜索功能也适用于这些字符,从 PDF 文件复制和粘贴也可以正常工作。使用默认的OT1编码,复制和粘贴字符 ö 会产生点和 o。

For example, with the default historic LaTeX encoding, the accented character ö is composed of the glyph o and dots, to be printed in the PDF file. With T1, an ö is a single glyph of the current font. Thus, LaTeX can also properly apply hyphenation rules to the words containing accented characters. The search feature of a PDF reader also works with those characters, and copying and pasting from the PDF file also works fine. With default OT1 encoding, copying and pasting the character ö would result in dots and an o.

提示

Tip

如果您注意到T1编码的默认字体质量下降,则您的安装可能缺少字体。在这种情况下,使用包管理器安装cm-super包,或切换到我们在以下部分中看到的字体之一。

If you notice a decrease in default font quality with T1 encoding, your installation may be missing fonts. In that case, install the cm-super package using the package manager, or switch to one of the fonts that we see in the following sections.

虽然这是输出编码,你可能还会遇到术语输入编码。现代的操作系统和编辑器支持UTF8Unicode – 一个行业扩展 ASCII 码的文本编码标准。LaTeX 直接支持 UTF8,所以我们不需要做任何事情。所以,如果你在旧书或网上的代码中遇到inputenc包,你可以忽略它。

While this is output encoding, you may also encounter the term input encoding. Modern operating systems and editors support UTF8Unicode – an industry standard for text encoding that extends the ASCII code. LaTeX directly supports UTF8, so we won't need to do anything. So, if you encounter the inputenc package in older books or code on the internet, you may omit it.

现在,我们将通过示例来了解一些不错的字体。它们都支持T1编码,因此在加载字体之前,请使用以下命令:

Now, we will take a look at some good fonts with examples. All of them supports T1 encoding, so before you load a font, use the following command:

\usepackage[T1]{fontenc}

\usepackage[T1]{fontenc}

在以下部分中,我们将探讨不同的字体。

In the following sections, we will explore the different fonts.

Latin Modern – 标准字体的替代品

Latin Modern – a replacement for the standard font

拉丁现代有被设计成看起来像默认的 LaTeX 字体,但是编码得到了改进,并且还进行了一些微调。Latin Modern 包含许多变音符号,而在 Computer Modern 中,这些字符由字母和重音构成。

Latin Modern has been designed to look like the default LaTeX font, but the encoding has been improved, and it has also received some more fine-tuning. Latin Modern contains many diacritic characters, whereas, with Computer Modern, such characters are built from letters and accents.

Latin Modern 拥有 72 种文本字体和 20 种数学字体,可用于所有字体系列、形状和粗细。

Latin Modern has 72 text fonts and 20 math fonts under the hood to work with all font families, shapes, and weights.

图 10.1中,我们看到了它的样子。

In Figure 10.1, we saw how it looks.

Kp-Fonts – 另一组广泛的字体

Kp-Fonts – another extensive set of fonts

Th Kp-字体集合从 Johannes Kepler 项目提供衬线、无衬线和等宽字体以及不同形状和粗细的数学符号字体​​。甚至存在大胆的扩展和组合,例如倾斜的衬线小型大写字母。

Th Kp-Fonts collection from the Johannes Kepler project provides serif, sans-serif, and monospaced fonts as well as mathematics symbol fonts in different shapes and weights. Even bold extended and combinations such as slanted serif small caps are present.

只需加载包即可使用这些字体:

Just load the package to use those fonts:

\usepackage{kpfonts}

\usepackage{kpfonts}

之前的示例将更改为以下内容:

The previous example will change to the following:

图 10.2 – 开普勒字体示例

图 10.2 – 开普勒字体示例

Figure 10.2 – Kepler font examples

Kp-字体提供具有相同字体指标的轻型版本。光印刷版本可能看起来不错,但那种浅色外观可能不适合在屏幕上阅读。

Kp-Fonts offers light versions with the same font metrics. The light versions might look nice in print, but that light appearance might not be perfect for reading on screen.

要切换到 light 字体集,请使用light选项加载包:

To switch to the light font set, load the package with the light option:

\usepackage[light]{kpfonts}

\usepackage[light]{kpfonts}

现在的外观会有所不同:

The look will be different now:

图 10.3 – Kepler 字体作为浅色版本

图 10.3 – Kepler 字体作为浅色版本

Figure 10.3 – Kepler font as a light version

现在,让我们看看在随附的专用字体包中单一风格。

Now, let's look at specialized font packages that come with a single style.

使用特定的字体系列

Using specific font families

我们将探索更多以自己的方式特别的 TeX 字体。我们将使用上一节中的\pangram宏和相应的系列命令进行测试。

We will explore many more TeX fonts that are special in their own way. We will use our \pangram macro from the previous section with the corresponding family command for testing.

衬线字体

Serif fonts

一条小线或附加到字母中较大笔画的笔画或符号称为衬线。一种字体经常使用此类衬线的字体称为衬线字体或衬线字体。

A small line or stroke attached to a larger stroke in a letter or symbol is called a serif. A font regularly using such serifs is called a serif font, or a serif typeface.

默认值衬线字体被称为Computer Modern Roman。Latin Modern 提供了一种非常相似的字体,您已经知道 Kp-Fonts serif 字体。其他包专门用于衬线字体,我们现在将看看其中的一些。

The default serif font is called Computer Modern Roman. Latin Modern provides a very similar font, and you already know the Kp-Fonts serif font. Other packages specialize in serif fonts, and we will now look at some of them.

时代罗马

Times Roman

newtx包_定义一个Times文本字体和一个匹配的数学字体。

The newtx package defines a Times text font and a matching math font.

它分为两部分,因此它们可以独立使用,例如当您想要不同的数学字体时。这就是我们以这种方式加载它的原因:

It's split into two parts, so they can be used independently, such as when you would like to have a different math font. That's why we load it in this way:

\usepackage{newtxtext}

\usepackage{newtxtext}

\usepackage{newtxmath}

\usepackage{newtxmath}

使用\pangram{\rmfamily}和我们的数学公式,我们得到以下内容:

With \pangram{\rmfamily} and our math formula, we get the following:

图片 10.4 – Times Roman 字体

图片 10.4 – Times Roman 字体

Figure 10.4 – A Times Roman font

如您所见,Times 是适用于多列文本的非常窄的字体与报纸一样,但不推荐用于单栏文本。宽文本行可读性较差。

As you can see, Times is a very narrow font suitable for multi-column text as in newspapers, but not so recommended for single-column text. Wide text lines would be less readable.

帕拉蒂诺

Palatino

newpx包_定义 Palatino 文本字体和匹配数学字体。这个包由两部分组成,独立使用,所以我们这样加载:

The newpx package defines a Palatino text font and a matching math font. This package consists of two parts for independent use, so we load it in this way:

\usepackage{newpxtext}

\usepackage{newpxtext}

\usepackage{newpxmath}

\usepackage{newpxmath}

这给了我们以下信息:

This gives us the following:

图片 10.5 – Palatino 字体

图片 10.5 – Palatino 字体

Figure 10.5 – A Palatino font

我们可以看到 Palatino 比 Times 宽得多。

We can see that Palatino is considerably wider than Times.

宪章

Charter

章程类似于默认的 Computer Modern 字体,但有点重。我们加载它,如图所示:

Charter is similar to the default Computer Modern font but a bit heavier. We load it as shown:

\usepackage{宪章}

\usepackage{charter}

为了适当的数学支持,使用charter选项加载mathdesign包,而不是直接加载charter

For proper math support, load the mathdesign package with the charter option instead of loading charter directly:

\usepackage[章程]{mathdesign}

\usepackage[charter]{mathdesign}

这导致以下结果:

This results in the following:

图 10.6 – Charter 和 mathdesign 字体

图 10.6 – Charter 和 mathdesign 字体

Figure 10.6 – Charter and mathdesign fonts

mathdesign 包的文本字体

Text fonts for the mathdesign package

除了章程mathdesign还可以通过\ usepackage [ utopia ]{mathdesign}Garamond字体通过\usepackage[garamond]{mathdesign} .

In addition to charter, mathdesign can load the Utopia font by means of \usepackage[utopia]{mathdesign} and the Garamond font by means of \usepackage[garamond]{mathdesign}.

新世纪教科书

New Century Schoolbook

newcent包_提供这种易于阅读的衬线字体,New Century Schoolbook

The newcent package provides this easy-to-read serif typeface, New Century Schoolbook:

\usepackage{newcent}

\usepackage{newcent}

为一个合适的数学字体,你可能希望加载傅里叶数学字体:

For a suitable math font, you may wish to load the Fourier math fonts:

\usepackage{fouriernc}

\usepackage{fouriernc}

他们在一起:

Here they are together:

图 10.7 – 新世纪教科书和傅里叶字体

图 10.7 – 新世纪教科书和傅里叶字体

Figure 10.7 – New Century Schoolbook and Fourier fonts

fouriernc包中的nc代表新世纪,因为它是设置一起使用。

nc in the fouriernc package stands for New Century because it's set up for being used together.

混凝土罗马

Concrete Roman

Concrete Roman字体可能在屏幕上看起来并不完美,但提供印刷质量高。只需加载具体包:

The Concrete Roman font may not look perfect on screen but offers high quality in print. Just load the concrete package:

\usepackage{具体}

\usepackage{concrete}

此外,对于 Concrete Roman,有一个匹配的数学字体包,称为concmath

Also, for Concrete Roman, there's a matching math font package, called concmath:

\usepackage{concmath}

\usepackage{concmath}

这些给了我们以下内容:

These give us the following:

图 10.8 – 具有数学支持的具体罗马字体

图 10.8 – 具有数学支持的具体罗马字体

Figure 10.8 – Concrete Roman font with math support

Concrete Roman 正立的整体符号和非衬线求和符号,显得与众不同。

With the upright integral sign and the non-serif summation sign, Concrete Roman looks distinctive.

书人

Bookman

Bookman是一个老式的serif 字体,由bookman包提供,已加载通过以下命令:

Bookman is an old-style serif font, provided by the bookman package, loaded by the following command:

\usepackage{书人}

\usepackage{bookman}

Kerkis字体是一种具有数学支持的bookman扩展,这意味着您可以改为加载它:

The Kerkis font is an extension of bookman with math support, meaning that you can load this instead:

\usepackage{kmath}

\usepackage{kmath}

\usepackage{kerkis}

\usepackage{kerkis}

我们得到以下信息:

We get the following:

图 10.9 – Kerkis,又名 Bookman,具有数学支持

图 10.9 – Kerkis,又名 Bookman,具有数学支持

Figure 10.9 – Kerkis, aka Bookman, with math support

甚至更多增强的 Bookman 版本以TeX Gyre Bonum的名义提供。不过,这一个,尤其是在数学支持下,更适合用作一种 OpenType 字体。在本章的最后一节,使用任意字体,我们将处理它。

An even more enhanced Bookman version is available under the name TeX Gyre Bonum. This one, though, especially with math support, is better used as an OpenType font. In the last section of this chapter, Using arbitrary fonts, we will deal with this.

字体名称

Font names

相同或相似的字体可以有非常不同的名称。这通常是出于法律原因,因为字体名称可以受到保护,但设计可以​​使用。

Same or similar fonts can have very different names. That's often for legal reasons, as the font names can be protected, but the design can be used.

无衬线字体

Sans-serif fonts

Sans-serif 字体只是不使用衬线的字体。他们可能看起来更直更清晰是幻灯片演示的不错选择。

Sans-serif fonts are simply fonts where no serifs are used. They may look straighter and clearer and are a good choice for slide presentations.

他们不当它们加粗时,它们看起来和衬线字体一样重。这就是为什么它们可能是标题的不错选择,但许多人认为使用传统衬线的连续文本更具可读性。

They don't appear as heavy as serif fonts when they are bold. That's why they may be a good choice for headings, but many believe that running text with traditional serifs is much more readable.

那就是KOMA-Script类在文档正文文本中默认使用衬线字体,而在标题中默认使用无衬线字体的原因。

That's the reason why KOMA-Script classes use a serif font in the document body text and a sans-serif font for the headings by default.

如果需要,可以通过以下命令将主体字体呈现为无衬线字体:

If required, the main body font could be rendered sans-serif by means of this command:

\renewcommand{\familydefault}{\sfdefault}

\renewcommand{\familydefault}{\sfdefault}

我们已经知道 Latin Modern 和 Kp-Fonts 提供无衬线字体。现在让我们再看看一些特定的无衬线字体。

We already know that Latin Modern and Kp-Fonts provide sans serif fonts. Let's now take another look at some specific sans-serif fonts.

阿雷夫

Arev

Arev是一种无衬线字体专为幻灯片演示而设计。名字意味着维拉向后,因为它扩展了Vera Sans字体,即源自Frutiger字体。Arev 添加数学支持。通过以下命令加载它:

Arev is a sans-serif font designed for slide presentations. The name means Vera backward, as it extends the Vera Sans font, which is derived from the Frutiger font. Arev adds math support. Load it by means of the following command:

\usepackage{arev}

\usepackage{arev}

文本和数学变成如下:

Text and math become the following:

图 10.10 – Arev,一种类似 Frutiger 的字体

图 10.10 – Arev,一种类似 Frutiger 的字体

Figure 10.10 – Arev, a Frutiger-like font

请注意,积分和求和符号仍然显示衬线,因为这很常见。

Note that integral and summation signs still show serifs, as this is very common.

电脑现代明​​亮

Computer Modern Bright

CM Bright已经源自计算机现代Sans Serif 有一个更轻的字体。cmbright包提供了这种字体以及一种浅色打字机字体和一种无衬线数学字体通过以下命令加载它:

CM Bright has been derived from Computer Modern Sans Serif to have a lighter font. The cmbright package provides this font together with a light typewriter font and a sans-serif math font. Load it by means of the following command:

\usepackage{cmbright}

\usepackage{cmbright}

我们的示例代码的输出如下:

The output of our sample code will be as follows:

图片 10.11 – Computer Modern Bright 字体

图片 10.11 – Computer Modern Bright 字体

Figure 10.11 – Computer Modern Bright font

如果你比较它与其他无衬线字体一起使用时,侵入性较小。它会最好不要搭配较重的衬线字体,因为粗细不同。

If you compare it with other sans serif fonts, it's less intrusive. It would be good not to match it with a heavier serif font because of the different weights.

库里尔

Kurier

一些无衬线字体看起来很相似,但你可以看到细节上的差异——看看图 10.12中的 Kurier 字体,例如字母 g 和数学符号。通过以下命令加载它:

Some sans-serif fonts appear to look similar, but you can see differences in detail – look at the Kurier font in Figure 10.12, for example, at the letter g and the math symbols. Load it by means of the following command:

\usepackage{库里尔}

\usepackage{kurier}

我们通过使用math选项获得数学支持:

We get math support by using the math option:

\usepackage[数学]{kurier}

\usepackage[math]{kurier}

编译我们的示例代码为我们提供了以下内容:

Compiling our example code gives us the following:

图片 10.12 – Kurier 字体

图片 10.12 – Kurier 字体

Figure 10.12 – The Kurier font

在这种情况下,我们甚至有没有衬线的积分符号和求和符号。

In this case, we have even integral and summation signs without serifs.

黑体字

Helvetica

经典的无衬线字体Helvetica简洁明了。你可能认识一个后代微软制作:Arial。加载这样的字体:

The classical sans-serif font Helvetica is simple and clean. You probably know a descendant made by Microsoft: Arial. Load the font this way:

\usepackage{helvet}

\usepackage{helvet}

如果使用缩放选项字体看起来太大,尤其是与衬线字体一起使用时。例如,要使其更小一些,您可以编写以下内容:

Use the scaled option if the font looks too big, especially when used together with a serif font. For instance, to get it a bit smaller, you can write the following:

\usepackage[缩放=0.95]{helvet}

\usepackage[scaled=0.95]{helvet}

Helvetica 不提供直接的数学支持,但sfmath包可以解决问题:

Helvetica doesn't provide direct math support, but the sfmath package comes to the rescue:

\usepackage{sfmath}

\usepackage{sfmath}

如果将sfmath包添加到文档序言中,当前的无衬线文本字体也将在数学公式中使用。在其他字体包之后加载它,所以它有机会检测到字体。可以在LaTeX Cookbook 的第 3 章“调整字体”中找到带有示例的更多解释、更多选项和sansmath包的替代方法。

If you add the sfmath package to your document preamble, the current sans-serif text font will also be used within math formulas. Load it after other font packages, so it has a chance to detect the font. Further explanations with examples, more options, and an alternative approach with the sansmath package can be found in Chapter 3, Adjusting Fonts, in the LaTeX Cookbook.

如本节所述加载helvetsfmath会产生以下输出:

Loading helvet and sfmath as in this section results in the following output:

图 10.13 – Helvetica 示例

图 10.13 – Helvetica 示例

Figure 10.13 – Helvetica example

sfmath作者的主页 https://dtrx.de/od/tex/sfmath.html,您可以找到更多信息。

At the sfmath author's home page, https://dtrx.de/od/tex/sfmath.html, you can find further information.

打字机字体

Typewriter fonts

打字机字体,又名等字体,是广泛使用对于来源代码,如本书所示。我们将看看其中的三个。

Typewriter fonts, a.k.a. monospaced fonts, are widely used for source codes, as in this book. We will look at three of them.

导游

Courier

快递是一个很广泛运行的打字机字体。我们可以加载它以下命令的手段:

Courier is a very wide-running typewriter font. We can load it by means of the following command:

\usepackage{快递}

\usepackage{courier}

然后,使用\ttfamily\texttt,我们将得到以下内容:

Then, with \ttfamily or \texttt, we will get the following:

图片 10.14 – Courier 字体

图片 10.14 – Courier 字体

Figure 10.14 – The Courier font

如果与您的标准文档字体相比,它看起来太大,您可以使用缩放选项加载couriers包(s表示缩放),例如:

If that looks too big compared to your standard document font, you can load the couriers package (s for scaled) with a scaled option, such as:

\usepackage[scaled=0.95]{信使}

\usepackage[scaled=0.95]{couriers}

这为我们提供了原始大小的 95% 的 Courier 字体。

This gives us the Courier font with 95% of its original size.

无忧无虑

Inconsolata

Inconsolata是一种非常漂亮的等宽字体,专为源代码列表而设计。易于阅读而且不像 Courier 那样宽。通过方式加载以下命令:

Inconsolata is a very nice, monospaced font designed for source code listings. It is easy to read and not as wide as Courier. Load it by means of the following command:

\usepackage{inconsolata}

\usepackage{inconsolata}

输出证明等宽字体可以很漂亮:

The output proves that monospaced fonts can be beautiful:

图片 10.15 – Inconsolata 字体

图片 10.15 – Inconsolata 字体

Figure 10.15 – The Inconsolata font

与 Courier 相比,它是无衬线字体。它还适用于缩放选项。

In contrast to Courier, it is sans-serif. It also works with a scaled option.

贝拉莫诺

Bera Mono

贝拉莫诺是另一种无衬线打字机字体。使用它以下命令的手段:

Bera Mono is another sans-serif typewriter font. Use it by means of the following command:

\usepackage{beramono}

\usepackage{beramono}

这是它的样子:

This is how it looks:

图片 10.16 – Bera Mono 字体

图片 10.16 – Bera Mono 字体

Figure 10.16 – The Bera Mono font

这里也是你可以指定一个缩放选项。

Here, also you can specify a scaled option.

书法字体

Calligraphic fonts

书法字体是具有流畅性的脚本字体类似的笔画手写。挑选两款漂亮的手写字体仔细看看。

Calligraphic fonts are script typefaces with fluid strokes similar to handwriting. Let's pick two beautiful handwriting fonts for a closer look.

书法

Calligra

我们照常加载字体:

We load the font as usual:

\usepackage{calligra}

\usepackage{calligra}

用于切换对于字体,我们可以在文本中使用\calligra命令。正如我们对本地切换命令的了解,该字体将一直有效,直到周围环境或组{}结束。它也适用于我们的\pangram宏,例如:

For switching to the font, we can use the \calligra command in the text. As we know about local switching commands, that font will be valid until a surrounding environment or group {} ends. It also works with our \pangram macro, such as:

\pangram{\calligra}

\pangram{\calligra}

这将打印以下内容:

This prints the following:

图片 10.17 – Calligra 手写字体

图片 10.17 – Calligra 手写字体

Figure 10.17 – The Calligra handwritten font

大写字母和带有下降字母的字母看起来格外俏皮。

Capital letters and letters with descenders look exceptionally playful.

新迈阿密

Miama Nueva

Miama Nueva写得很美上升者和下降者。通过方式加载以下命令:

Miama Nueva writes beautiful ascenders and descenders. Load it by means of the following command:

\usepackage{迈阿密}

\usepackage{miama}

然后,\fmmfamily命令切换到该字体。同样,如果您想将字体限制为仅一段文本,请在组{}或环境中使用它。我们可以再次使用我们的\pangram宏:

Then, the \fmmfamily command switches to that font. Again, use it within a group {} or an environment if you would like to limit the font to just a piece of text. We can use our \pangram macro again:

\pangram{\fmmfamily}

\pangram{\fmmfamily}

写作是阅读的乐趣:

The writing is a pleasure to read:

图 10.18 – Miama Nueva 手写字体

图 10.18 – Miama Nueva 手写字体

Figure 10.18 – The Miama Nueva handwritten font

Miama Nueva 是非常迷人,例如,在婚礼请柬上。

Miama Nueva is very charming, for example, on invitation cards for weddings.

探索 LaTeX 字体的整个世界

Exploring the whole world of LaTeX fonts

大概是浏览 LaTeX 字体的最佳地点是The LaTeX Font Catalogue您可以通过https://www.tug.org/FontCatalogue/在线访问它。该目录旨在展示所有可免费获得的 LaTeX 字体。它基于 TeX Live。它显示了可视示例和所需的代码,以及更多有用的信息。只需选择一个类别,浏览可视化预览,然后单击一种字体即可查看一些示例、用法和代码。

Probably the best place to browse LaTeX fonts is The LaTeX Font Catalogue. You can visit it online at https://www.tug.org/FontCatalogue/. The catalog aims to present all freely available fonts for LaTeX. It is based on TeX Live. It shows visual examples and the required code, along with further useful information. Just choose a category, browse a visual preview, and click on a font to see some examples, usage, and code.

您可以使用其他字体 - 这就是我们现在要去的地方。

There are additional fonts you can use – that's where we will be going now.

使用任意字体

Using arbitrary fonts

任意是一个措辞有点宽泛,但其含义在今天仍然有效,我们可以在数以千计甚至没有为 LaTeX 准备的字体中进行选择。这可能是操作系统字体、TrueType 字体或现代 OpenType 字体。

Arbitrary is a bit broadly worded, but the meaning is valid as today, we can choose among many thousands of fonts that were not even prepared for LaTeX. That may be operating system fonts, TrueType fonts, or modern OpenType fonts.

让我们使用一些在 Microsoft Windows 10 计算机上可用的字体。

Let's use some fonts that are available on a Microsoft Windows 10 computer.

选择主要字体

Selecting the main font

我们可以通过 Windows 开始菜单打开设置/字体,或者查看文件夹C:\Windows\Fonts以查看已安装的字体。Segoe UI字体显示可用有几个名字,所以让我们选择Segoe UI Semilight。我们将看看它是否难以使用:

We can either open Settings / Fonts via the Windows start menu or look into the folder C:\Windows\Fonts to see the installed fonts. The Segoe UI font appears available with several names, so let's choose Segoe UI Semilight. We will see whether it's hard to use:

  1. 开始一个新文档:

    \文档类{文章}

  2. Start a new document:

    \documentclass{article}

  3. 加载fontspec包,因为它为我们提供了字体选择命令:

    \usepackage{fontspec}

  4. Load the fontspec package because it provides us with font selection commands:

    \usepackage{fontspec}

  5. 选择主要字体:

    \setmainfont{Segoe UI Semilight}

  6. Choose the main font:

    \setmainfont{Segoe UI Semilight}

  7. 用一些大文本写文档正文:

    \开始{文档}

    \大的

    敏捷的棕色狐狸跳过了懒狗。1234567890

    \end{文档}

  8. Write the document body with some large text:

    \begin{document}

    \large

    The quick brown fox jumps over the lazy dog. 1234567890

    \end{document}

  9. 现在我们进入一个新的方式:选择LuaLaTeXXeLaTeX作为编译引擎。在 TeXworks 中,这是排版按钮旁边的下拉列表,如下所示:
    图 10.19 – 选择 LuaLaTeX

    图 10.19 – 选择 LuaLaTeX

  10. Now we enter a new way: choose either LuaLaTeX or XeLaTeX as the compiling engine. In TeXworks, this is a drop-down list right next to the Typeset button, as shown here:

    Figure 10.19 – Selecting LuaLaTeX

  11. 点击Typeset编译,看看我们得到了什么:
  12. Click on Typeset to compile, and see what we get:
图 10.20 – 来自 Microsoft Windows 10 的 Segoe UI Semilight

图 10.20 – 来自 Microsoft Windows 10 的 Segoe UI Semilight

Figure 10.20 – Segoe UI Semilight from Microsoft Windows 10

那种字体选择非常简单:加载一个包,使用一个命令。现在让我们在文档中使用多种字体。

That font selection was quite easy: loading one package, using one command. Let's now do it with multiple fonts in a document.

选择多个字体系列

Selecting multiple font families

我们可以在 Windows 上寻找更多已经安装的字体。我们可以通过Windows 开始菜单中的设置/字体或通过查看C:\Windows\Fonts文件夹再次执行此操作。这一次,我们将选择以下内容:

We can look for further already installed fonts on Windows. We can do that again either via Settings / Fonts in the Windows Start menu or by looking in the C:\Windows\Fonts folder. This time, we will choose the following:

  • Cambria 作为我们想要衬线的主要字体
  • Cambria as the primary font that we want to be serif
  • Segoe UI 作为无衬线字体
  • Segoe UI as the sans-serif font
  • Lucida Console 作为打字机字体
  • Lucida Console as the typewriter font
  • Cambria Math 作为衬线数学字体
  • Cambria Math as the serif math font

所有只是 Windows 安装的字体。

All are just Windows-installed fonts.

因此,让我们创建一个显示所有这四种字体的文档:

So, let's create a document that displays all these four fonts:

  1. 开始一个新文档并再次输入我们的\pangram宏以便于测试:

    \文档类{文章}

    \newcommand{\pangram}[1]{{#1 敏捷的棕色狐狸

    跳过懒狗。1234567890\par}}

  2. Start a new document and enter our \pangram macro again for easier testing:

    \documentclass{article}

    \newcommand{\pangram}[1]{{#1 The quick brown fox

    jumps over the lazy dog. 1234567890\par}}

  3. 加载fontspec包和unicode-math包。后者用于选择数学字体,如图:

    \usepackage{fontspec}

    \usepackage{unicode-数学}

  4. Load the fontspec package and the unicode-math package. The latter is for selecting the math font, as shown:

    \usepackage{fontspec}

    \usepackage{unicode-math}

  5. 设置我们在本节开头计划的字体。我们使用一个自动缩放字体的可选参数,因此它们的小写字母高度与主字体小写字母高度匹配,如下所示:

    \setmainfont{坎布里亚}

    \setsansfont{Segoe UI}[Scale=MatchLowercase]

    \setmonofont{Lucida 控制台}[Scale=MatchLowercase]

    \setmathfont{坎布里亚数学}[Scale=MatchLowercase]

  6. Set the fonts as we planned at the beginning of this section. We use an optional argument that automatically scales the fonts, so their lowercase letter height matches the main font lowercase letter heights, as follows:

    \setmainfont{Cambria}

    \setsansfont{Segoe UI}[Scale=MatchLowercase]

    \setmonofont{Lucida Console}[Scale=MatchLowercase]

    \setmathfont{Cambria Math}[Scale=MatchLowercase]

  7. 然后,再次编写测试文档主体以查看可用字体:

    \开始{文档}

    \大的

    \pangram{\rmfamily}

    \pangram{\sffamily}

    \pangram{\ttfamily}

    \[

      \int_a^b \! f(x) \, dx = \lim_{\Delta x \rightarrow 0}

      \sum_{i=1}^{n} f(x_i) \,\Delta x_i

    \]

    \end{文档}

  8. Then, write a test document body again to view the available fonts:

    \begin{document}

    \large

    \pangram{\rmfamily}

    \pangram{\sffamily}

    \pangram{\ttfamily}

    \[

      \int_a^b \! f(x) \, dx = \lim_{\Delta x \rightarrow 0}

      \sum_{i=1}^{n} f(x_i) \,\Delta x_i

    \]

    \end{document}

  9. LuaTeXXeLaTeX选为编译器。单击排版并查看:
  10. Keep LuaTeX or XeLaTeX selected as the compiler. Click on Typeset and take a look:
图片 10.21 – 各种 Microsoft Windows 字体

图片 10.21 – 各种 Microsoft Windows 字体

Figure 10.21 – Various Microsoft Windows fonts

我们有Cambria 作为默认文档字体,每当我们切换到 sans-serif 时,我们都会得到 Segoe UI,当我们用打字机字体编写代码清单时,会选择 Lucida Console。此外,数学公式现在使用 Cambria Math 而不是默认的 Computer Modern 字体打印。这种简单的字体选择实际上是 LaTeX 的一个演变,并且由于扩展的字体支持而值得考虑LuaLaTeXXeLaTeX 。两者都支持 OpenType 和 Truetype 字体,它们还不能用于pdfLaTeX

We got Cambria as the default document font, and whenever we switch to sans-serif, we get Segoe UI, and when we write code listings in typewriter font, Lucida Console is chosen. Also, math formulas are now printed in Cambria Math instead of the default Computer Modern font. This easy font selection is actually quite an evolution in LaTeX, and it's worth considering LuaLaTeX or XeLaTeX just because of the extended font support. Both support OpenType and Truetype fonts, which do not yet work with pdfLaTeX.

XeLaTeX的开发重点是直接使用系统字体,这在pdfLaTeX中是不可能的。LuaLaTeX首先将 Lua 语言作为脚本引擎添加到 LaTeX 中,并且随着时间的推移它也获得了更好的字体支持。在不处理它们的高级功能的情况下,当涉及到我们没有与pdfLaTeX一起使用的包的字体时,我们可以简单地选择其中之一。

XeLaTeX has been developed with a focus on using system fonts directly, which was impossible with pdfLaTeX. LuaLaTeX started by adding the Lua language as a scripting engine to LaTeX, and it also got better font support over time. Without dealing with their advanced features, we can simply choose one of them when it comes to fonts where we don't have a package for use with pdfLaTeX.

概括

Summary

现在我们可以使用不同的文本和数学字体。我们的文档不再需要看起来像简单的默认字体 LaTeX 文章或书籍。

Now we can use different text and math fonts. Our documents no longer need to look like simple default font LaTeX articles or books.

我们了解了安装和选择字体集和特定字体,并对好的字体包进行了调查。对于带有现成示例的一些高级字体任务,您可以查看LaTeX Cookbook中的第 3 章调整字体

We learned about installing and choosing font sets and specific fonts and made a survey of good font packages. For some advanced font tasks with ready-to-use examples, you can take a look at Chapter 3, Adjusting Fonts, in the LaTeX Cookbook.

现在,让我们从字体回到 LaTeX,我们将在下一章学习如何开发和管理更大的文档。

Now, let's go back from fonts to LaTeX, and we will learn how to develop and manage larger documents in the next chapter.

第 11 章:开发大型文档

Chapter 11: Developing Large Documents

本书第一章声称 LaTeX 可以轻松处理大型文档。当您创建大量文档时,您会注意到 LaTeX 一直在可靠地完成它的工作。对于计算机来说,源代码的格式如何并不重要。但对于作为开发人员的您来说,保持源文档易于管理是必不可少的。毕竟,它可能包含数百页和数千行。

The first chapter of this book claimed that LaTeX handles large documents easily. When you create extensive documents, you will notice that LaTeX keeps on doing its job reliably. For the computer, it doesn't matter how the source code is formatted. But for you, as the developer, it's essential to keep your source document manageable. After all, it may consist of hundreds of pages with thousands of lines.

到本章结束时,我们将能够处理包含多个文件、一个标题页以及单独编号的封面和封底部分的大型文档项目。

By the end of this chapter, we will be able to handle a big document project with several files, a title page, and separately numbered front matter and back matter parts.

在本章中,我们将了解以下内容:

In this chapter, we will learn about the following:

  • 拆分输入
  • Splitting the input
  • 创建正面和背面材料
  • Creating front and back matter
  • 设计标题页
  • Designing a title page
  • 使用模板
  • Working with templates

这是在撰写论文、书籍或广泛报告的道路上迈出的一大步。

That's a big step forward on the way to writing a thesis, a book, or an extensive report.

让我们从基于多个文件构建文档开始。

Let's begin by building a document based on several files.

技术要求

Technical requirements

您可以使用本地 LaTeX 安装,也可以在https://latexguide.org/chapter-11在线编译示例代码。

You can use a local LaTeX installation, or you can compile the example code online at https://latexguide.org/chapter-11.

该代码可在 GitHub 上找到,网址为https://github.com/PacktPublishing/LaTeX-Beginner-s-Guide-2nd-Edition-/tree/main/Chapter_11_-_Developing_Large_Documents

The code is available on GitHub at https://github.com/PacktPublishing/LaTeX-Beginner-s-Guide-2nd-Edition-/tree/main/Chapter_11_-_Developing_Large_Documents.

在本章中,我们将使用以下包:amsmathamsthmbabelblindtextfontencgeometrylmodernmicrotypenatbibtocbibind

In this chapter, we will use the following packages: amsmath, amsthm, babel, blindtext, fontenc, geometry, lmodern, microtype, natbib, and tocbibind.

我们还将简要查看pdfpages标题包。

We will also briefly look at the pdfpages and titling packages.

拆分输入

Splitting the input

分而治之——这可能是我们现在的座右铭。我们将弄清楚如何将文档分解为几个子文件。因此,在我们写作的同时,我们将能够管理一个巨大的项目,该项目由许多单独文件中的章节组成。

Divide and conquer—this could be our motto now. We will figure out how to break down a document into several sub-documents. Thus, while we are writing, we will be able to manage a huge project consisting of many chapters in separate files.

首先,我们将通过交换序言来分离设置和正文。其次,我们将在单独的文件中编写章节,然后将它们包含在内。

Firstly, we will separate settings and body text by swapping out the preamble. Secondly, we will write chapters in separate files and include them afterward.

我们将开始编写有关方程和方程系统的详细文档。结果应该是论文或书籍的风格。我们可以使用第 9 章的最后一个示例,编写数学公式,我们在其中处理了有关方程式的定理。

We will begin to write a detailed document regarding equations and equation systems. The result should be in the style of a thesis or a book. We can use the last example of Chapter 9, Writing Math Formulas, where we dealt with theorems concerning equations.

我们将逐步创建几个文件:

We will create several files, step by step:

  1. 创建一个新文档。在其中,加载所有包并指定选项,就像我们在前几章的序言中所做的那样。使用我们已经了解的所有有用的包:

    \usepackage[english]{babel}

    \usepackage[T1]{fontenc}

    \usepackage{lmodern}

    \usepackage{微型}

    \usepackage{natbib}

    \usepackage{tocbibind}

    \usepackage{amsmath}

    \usepackage{amsthm}

    \newtheorem{thm}{Theorem}[章节]

    \newtheorem{lem}[thm]{引理}

    \theoremstyle{定义}

    \newtheorem{dfn}[thm]{定义}

  2. Create a new document. Inside this, load all the packages and specify the options, like we did in our preambles in the previous chapters. Use all the beneficial packages that we have already learned about:

    \usepackage[english]{babel}

    \usepackage[T1]{fontenc}

    \usepackage{lmodern}

    \usepackage{microtype}

    \usepackage{natbib}

    \usepackage{tocbibind}

    \usepackage{amsmath}

    \usepackage{amsthm}

    \newtheorem{thm}{Theorem}[chapter]

    \newtheorem{lem}[thm]{Lemma}

    \theoremstyle{definition}

    \newtheorem{dfn}[thm]{Definition}

  3. 将此文档保存在名称preamble.tex下。
  4. Save this document under the name preamble.tex.
  5. 开始另一个新文档并复制第 9 章“编写数学公式”的“编写定理和定义”部分的定理示例中“方程式”章节的内容:

    \chapter{方程式}

    \section{二次方程}

    \开始{dfn}

      二次方程是以下形式的方程

      \begin{方程式}

        \标签{四边形}

        ax^2 + bx + c = 0

      \end{方程式}

      其中 \( a, b \) 和 \( c \) 是常量

      和 \( a \neq 0 \)。

      \结束{dfn}

  6. Start another new document and copy the contents of the Equations chapter in the theorem example of the Writing theorems and definitions section of Chapter 9, Writing Math Formulas:

    \chapter{Equations}

    \section{Quadratic equations}

    \begin{dfn}

      A quadratic equation is an equation of the form

      \begin{equation}

        \label{quad}

        ax^2 + bx + c = 0

      \end{equation}

      where \( a, b \) and \( c \) are constants

      and \( a \neq 0 \).

      \end{dfn}

  7. 保存这个名为chapter1.tex 的文件。
  8. Save this document under the name chapter1.tex.
  9. 为下一章创建另一个文档,写下章节标题等等,包括几个部分。将其保存为chapter2.tex

    \chapter{方程系统}

    \section{线性系统}

    ...

    \section{非线性系统}

    ...

  10. Create another document for the next chapter, write the chapter heading and some more, including a few sections. Save it as chapter2.tex:

    \chapter{Equation Systems}

    \section{Linear Systems}

    ...

    \section{Non-linear Systems}

    ...

  11. 现在我们将构建顶级文档。创建另一个名为equations.tex的文件。这一个以\documentclass命令开始并列出序言和包含的章节:

    \文档类{书籍}

    \输入{序言}

    \开始{文档}

    \目录

    \包括{第一章}

    \包括{第2章}

    \end{文档}

  12. Now we will construct the top-level document. Create another file called equations.tex. This one starts with the \documentclass command and lists the preamble and the chapters for inclusion:

    \documentclass{book}

    \input{preamble}

    \begin{document}

    \tableofcontents

    \include{chapter1}

    \include{chapter2}

    \end{document}

  13. 编译文件两次。请记住,此操作是获取目录所必需的。现在,检查内容以检查所有内容是否都在正确的位置:
  14. Compile the document twice. Remember that this action is necessary to get the table of contents. For now, check the contents to check that everything is in its correct place:
图 11.1 – 目录

图 11.1 – 目录

Figure 11.1 – Table of contents

我们构建了一个名为equations.tex 的顶级文档。将其称为main.tex或类似的名称很诱人。但是,由于此文件名决定了生成的 PDF 文档的名称,因此我们选择了一个有意义的名称。

We constructed a top-level document that we called equations.tex. It's tempting just to call it main.tex, or something similar. However, as this filename determines the name of the resulting PDF document, we chose a meaningful name.

这是我们项目的框架。这是一个普通的 LaTeX 文档,但我们尽可能地缩小了它并使用两个命令导入外部.tex文件:

This is the framework of our project. It's an ordinary LaTeX document, but we reduced it as much as possible and used two commands to import external .tex files:

  • \input读入另一个文件,就像我们输入它一样。
  • \input reads in another file, just as if we had typed it.
  • \include也读入外部文件,但在前后自动插入\clearpage 。
  • \include also reads in an external file but automatically inserts \clearpage before and after.

后者为您提供更多,所以让我们仔细看看——我们将首先处理更简单的\input命令。

The latter offers more to you, so let's have a closer look—we will treat the simpler \input command first.

包括小段代码

Including small pieces of code

读取文件的最简单命令如下:

The simplest command to read in a file is as follows:

\输入{文件名}

\input{filename}

当 LaTeX 遇到这个命令时,它会读入名为filename 的文件,就好像它的内容已经在那个时候被键入一样。因此,LaTeX 编译器处理该文件中的所有命令。你甚至可以嵌套\input——这个命令可以在包含的文件中使用。

When LaTeX encounters this command, it reads in the file with the name filename, exactly as if its contents have been typed at that point. Accordingly, the LaTeX compiler processes all commands in this file. You can even nest \input—this command may be used inside an included file.

如果文件名没有扩展名,LaTeX 会假定扩展名为.tex,因此它会插入filename.tex。您还可以指定路径,相对路径或绝对路径。当反斜杠开始命令时,在路径名中使用斜杠/而不是反斜杠\

If the filename doesn't have an extension, LaTeX assumes the extension .tex , so it inserts filename.tex. You may also specify a path, relative or absolute. As a backslash begins a command, use slashes / instead of backslashes \ in path names.

使用相对路径名使移动和复制项目更易于管理。

Using relative path names makes moving and copying a project more manageable.

如果您希望将序言放入单独的文件中,请使用\input 。除了保持根文档的清洁之外,还可以轻松地复制和调整单独的序言以便在另一个文档中使用。

Use \input if you wish to put your preamble into a separate file. Besides keeping your root document clean, a separate preamble can easily be copied and adjusted for use in another document.

但是单纯的拆分输入还不算文档管理。例如,虽然您可以注释掉选定的\input行以进行部分编译,但页码、章节等的编号可能会被破坏,并且对省略的文档部分的交叉引用将失败。

However, simply splitting and inputting is not yet considered document management. For instance, though you could comment out selected \input lines for partial compilation, the numbering of pages, sections, and so on may be ruined, and cross-referencing to omitted document parts would fail.

有更好的方法——让我们看看\include命令。

There's a better way—so let's look at the \include command.

包括文档的较大部分

Including bigger parts of a document

当它涉及到包括一个或多个页面时,这个命令被证明是有用的:

When it comes to including one or more pages, this command proves to be useful:

\include{文件名}

\include{filename}

该参数的处理方式与\input相同。但是,有一些重要的区别:

The argument is treated the same way as \input. However, there are some important differences:

  • \include隐含地开始新页面。\include{filename}行为如下:

    \clearpage

    \include{文件名}

    \clearpage

  • \include implicitly starts new pages. \include{filename} behaves like this:

    \clearpage

    \include{filename}

    \clearpage

  • 这使得\include对页面范围如章节或部分很有用。一个结果是您只能在\begin{document}之后使用\include
  • This makes \include useful for page ranges such as chapters or sections. One consequence is that you may use \include only after \begin{document}.
  • \include不能嵌套。您仍然可以在包含的文档中使用\input,尽管进一步复杂化结构可能不是一个好主意。
  • \include cannot be nested. You could still use \input within included documents, though it might not be a good idea to complicate the structure further.
  • 最重要的是,\include支持一种机制来选择要编译文档的哪些部分——因此我们使用另一个命令,即\includeonly
  • Most importantly, \include supports a mechanism for choosing which parts of the document you wish to compile—so we come to another command, namely, \includeonly.

让我们看看\includeonly是如何工作的。

Let's see how \includeonly works.

编译文件的一部分

Compiling parts of a document

这样的用于\input\include的部分文档不能单独编译:您需要一个指定文档类的根文档。

Such a partial document, intended for \input or \include, cannot be compiled standalone: you need a root document that specifies the document class.

但是,一旦您在编译根文档时使用\include交换了文档的某些部分,您可以指定此命令包含哪些部分:

However, once you swapped out parts of the document using \include while compiling your root document, you may specify which parts are included by this command:

\includeonly{文件列表}

\includeonly{file list}

我们只能在序言中使用\includeonly,换句话说,在\begin{document}之前。

We can use \includeonly only in the preamble, in other words, before \begin{document}.

该参数可以是逗号分隔的文件名列表。如果在此参数中未指定文件name.tex,则\include{name}不会插入此文件,而是表现得像\clearpage。这允许从编译中排除块或整个章节。如果您处理一个巨大的文档,如果您选择只包含当前章节,那么这会加快编译速度,同时以这种方式保留排除章节的标签和参考。

The argument may be a comma-separated list of filenames. If a file, name.tex, is not specified within this argument, \include{name} would not insert this file but behave like \clearpage instead. This allows the exclusion of chunks or whole chapters from compiling. If you work on a huge document, this speeds up compilation if you choose to include just your current chapter while keeping the labels and references of the excluded chapter this way.

您可能会注意到 LaTeX 会为包含的每个.tex文件生成一个.aux文件。LaTeX 仍然会读取所有那些包含章节和页码等信息的.aux文件。当然,包含的文件至少需要编译一次。这样,即使您暂时排除章节,交叉引用页码、章节、节等的编号也将保持不变。

You may notice that LaTeX produces an .aux file for each .tex file included. LaTeX still reads in all those .aux files containing information such as chapter and page numbers. Of course, the included files need to be compiled at least once. This way, cross-referencing the numbering of pages, chapters, sections, and so on will remain intact even if you temporarily exclude the chapters.

尝试一下——添加以下内容:

Try it out—add the following:

\includeonly{第2章}

\includeonly{chapter2}

将它添加到equations.tex中的序言并编译。结果将只是第二章保持正确的编号。使用 Acrobat Reader 查看这里的输出:

Add it to your preamble in equations.tex and compile. The result will be just the second chapter keeping the correct numbering. Take a look at the output here with Acrobat Reader:

图 11.2 – 我们的文档只有第 2 章

图 11.2 – 我们的文档只有第 2 章

Figure 11.2 – Our document with Chapter 2 only

在图 11.2的顶部,您可以看到3/3页,而不是当前章节第一个示例中的 5 页。在左侧,您可以看到三页的缩略图,第三页是我们的第 2 章。在右侧,您会看到第 2 章,底部有正确的页码5 。这向我们表明,第 1 章未包含在此处,而仅包含我们希望的第 2 章。此外,页码仍与完整文档中的页码相同,而原始章节的编号也没有变化。

At the top of Figure 11.2, you can see 3/3 pages instead of 5 pages in the first example of the current chapter. On the left side, you see three pages as thumbnails, and the third page is our Chapter 2. On the right side, you see Chapter 2, with the correct page number 5 at the bottom. This shows us that Chapter 1 is not included here, but only Chapter 2, as we desired. Also, the page numbers are still the same as they are in the full document, while the original chapter and section numbers are also unchanged.

如果您处理包含许多章节和使用\includeonly只包含您正在处理的一章。

Compiling time is significantly shorter if you work on a huge document with many chapters and use \includeonly to include just a single chapter that you are working on.

最后,当你完成你的工作时,只需注释掉后面的命令即可排版你的完整文档。

Finally, just comment the latter command out to typeset your complete document when you finish your work.

当然,您可以使用\include而不使用\includeonly只是为了将大文档拆分成文件。

Of course, you can use \include without \includeonly just for splitting a large document into files.

现在让我们回到一个更大文档的结构。

Let's now return to the structure of a bigger document.

创建正面和背面材料

Creating front and back matter

与报告相比,书籍通常以介绍性材料开始,例如版权信息、前言、致谢或献词。这部分包括扉页和目录,称为封面

In contrast to reports, books often begin with introductory material such as copyright information, a foreword, acknowledgments, or a dedication. This part, including the title page and the table of contents, is called the front matter.

最后,一本书可能包括后记和支持材料,例如参考书目和索引。这部分称为背物

At the end, a book might include an afterword and supporting material such as a bibliography and an index. This part is called the back matter.

book和其他一些类,例如scrbookmemoir,直接支持这种分段。通常,这种分段的预期结果是页码和章节的编号不同。让我们看看它是如何工作的。

The book class and some other classes, such as scrbook and memoir, support this kind of sectioning directly. Often, desired consequences of this sectioning are differences in the numbering of pages and chapters. Let's see how it works.

我们的书将从奉献开始。前言将包括目录、图表列表和献词。封面的所有页数都将用罗马数字编号。最后,我们添加了一个提供补充证明的附录,我们希望将其放在主要章节之外:

Our book will begin with a dedication. The front matter will consist of the table of contents, lists of tables and figures, and a dedication. All the pages of the front matter will be numbered with Roman numerals. Finally, we add an appendix providing supplementary proofs, which we like to present outside the main chapters:

  1. 创建文件dedication.tex

    \chapter{奉献}

    这本书献给最伟大的人之一

    有史以来的数学家:卡尔·弗里德里希·高斯。

    没有他,就不可能有这本书。

  2. Create a file, dedication.tex:

    \chapter{Dedication}

    This book is dedicated to one of the greatest

    mathematicians of all time: Carl Friedrich Gauss.

    Without him, this book wouldn't have been possible.

  3. 创造文件proofs.tex

    \chapter{证明}

    ...

  4. Create a file, proofs.tex:

    \chapter{Proofs}

    ...

  5. 延长主文件equations.tex,通过突出显示的行:

    \文档类{书籍}

    \输入{序言}

    \开始{文档}

    \frontmatter

    \include{奉献}

    \目录

    \listoftables

    \listoffigures

    \主要问题

    \包括{第一章}

    \包括{第2章}

    \背景

    \include{校样}

    \nocite{*}

    \bibliographystyle{plainnat}

    \书目{例子}

    \end{文档}

  6. Extend the main file, equations.tex, by means of the highlighted lines:

    \documentclass{book}

    \input{preamble}

    \begin{document}

    \frontmatter

    \include{dedication}

    \tableofcontents

    \listoftables

    \listoffigures

    \mainmatter

    \include{chapter1}

    \include{chapter2}

    \backmatter

    \include{proofs}

    \nocite{*}

    \bibliographystyle{plainnat}

    \bibliography{example}

    \end{document}

  7. 尽你所能在最后突出显示的行中看到,我们重新使用了第 8 章中的example.bib文件,列出内容和参考文献。点击Typeset to compile,运行 BibTeX,然后再次编译。查看列出目录中的编号:
  8. As you can see in the last highlighted line, we re-used the example.bib file from Chapter 8, Listing Contents and References. Click on Typeset to compile, run BibTeX, and compile again. Check out the numbering within the table of contents:
图 11.3 – 复杂文档的目录

图 11.3 – 复杂文档的目录

Figure 11.3 – Table of contents of a complex document

我们看到 LaTeX 以罗马数字打印目录页的页码。这适用于所有前页。此外,即使我们没有使用带星号的命令\chapter*,前后的所有章节都没有编号。

We saw that LaTeX printed the page number of the contents page in Roman numerals. This applies to all front-matter pages. Further, all the chapters in the front and back matter are unnumbered even though we did not use the starred command, \chapter*.

为此,三个命令—— \frontmatter\mainmatter\backmatter负责。他们开始一个新页面并按以下方式修改页面和章节编号:

For this, the three commands – \frontmatter, \mainmatter, and \backmatter, are responsible. They start a new page and modified both the page and chapter numbering in the following way:

  • \frontmatter:页面用小写罗马数字编号。章节生成表格内容条目但没有得到数字。
  • \frontmatter: Pages are numbered with lowercase Roman numerals. Chapters generate a table of contents entry but don't get a number.
  • \mainmatter:页面用阿拉伯数字编号。章节编号并生成目录条目。
  • \mainmatter: Pages are numbered with Arabic numerals. Chapters are numbered and produce a table of contents entry.
  • \backmatter:页面是用阿拉伯数字编号。章节生成目录条目但没有编号。
  • \backmatter: Pages are numbered with Arabic numerals. Chapters generate a table of contents entry but don't get a number.

与book类一样,scrbookmemoir类提供具有非常相似行为的相同命令。

Like the book class, the scrbook and memoir classes provide the same commands with very similar behavior.

大型文档通常以扉页开头。我们现在将看到如何在 LaTeX 中制作标题页。

A large document usually starts with a title page. We will now see how to produce a title page in LaTeX.

设计标题页

Designing a title page

我们可以使用\maketitle快速创建一个好看的标题页,就像我们在第 2 章格式化文本和创建宏中所做的那样。文档类通常提供此命令来生成合适的预格式化标题页。或者,您可以使用titlepage环境来自由设计其布局。所以,让我们为我们的方程式书设计一个漂亮的扉页。

We can quickly create a good-looking title page using \maketitle, as we did in Chapter 2, Formatting Text and Creating Macros. Document classes usually offer this command to generate a suitable pre-formatted title page. Alternatively, you could use a titlepage environment to design its layout freely. So, let's design a nice title page for our book of equations.

第 2 章格式化文本和创建宏中,我们已经使用了一些格式化命令,例如\centering,以及字体大小和形状命令,例如\Huge\bfseries,来格式化标题。我们将在titlepage环境中进行类似的操作:

In Chapter 2, Formatting Text and Creating Macros, we have already used some formatting commands, such as \centering, and font size and shape commands, such as \Huge and \bfseries, to format a title. We will do it similarly within a titlepage environment:

  1. 创建一个文件title.tex,内容如下:

    \开始{titlepage}

    \raggedleft

    {\大作者\\[1in]}

    {\large 大书\\}

    {\Huge\scshape 方程\\[.2in]}

    {\大量包含数百个示例和解决方案\\}

    \v填充

    {\itshape 2011, 出版公司}

    \结束{titlepage}

  2. Create a file, title.tex, with the following content:

    \begin{titlepage}

    \raggedleft

    {\Large The Author\\[1in]}

    {\large The Big Book of\\}

    {\Huge\scshape Equations\\[.2in]}

    {\large Packed with hundreds of examples and solutions\\}

    \vfill

    {\itshape 2011, Publishing company}

    \end{titlepage}

  3. 在\frontmatter之后添加这一行:

    \包括{标题}

  4. Add this line right after \frontmatter:

    \include{title}

  5. 我们的最后一本书将采用 A5 格式,扉页也将采用 A5 格式。因此,让我们将其添加到序言中:

    \usepackage[a5paper]{几何}

  6. Our final book will be in A5 format, and so will the title page. Therefore, let's add that to the preamble:

    \usepackage[a5paper]{geometry}

  7. 单击“排版”进行编译。现在我们有了一个扉页:
  8. Click on Typeset to compile. Now we've got a title page:
图 11.4 – 标题页

图 11.4 – 标题页

Figure 11.4 – A title page

titlepage环境将其内容排版在单独的页面上虽然这个扉页将像任何其他页面一样编号,页码不会打印在该页面上。

The titlepage environment typesets its contents on a separate page. Although this title page will be numbered like any other page, the page number won't be printed on that page.

在这个环境中,我们使用了一些基本的 LaTeX 字体命令来修改字体大小和形状。通过用花括号分组,我们限制了这些命令。诸如\\[.2in]之类的换行符会在下一行之前产生更多空间。\vfill插入一个灵活的垂直空间,它尽可能地伸展以填满页面。这样,我们将最后一行放在页面末尾。

Within this environment, we used some basic LaTeX font commands to modify the font size and shape. By grouping with curly braces, we limited those commands. Line breaks such as \\[.2in] cause some more space before the following line. \vfill inserts a flexible vertical space, which stretches as much as possible to fill the page. This way, we put the last line off to the end of the page.

请注意,此页面与文档中的其他页面具有相同的页面尺寸。这意味着,在双面书中,它是右手页。因此,您可能会注意到左和右边距,这可能看起来不受欢迎,尤其是当您的标题位于中间时。然而,解释很简单:这个扉页是用来做内页的,而不是封页。内扉页当然是右侧页面。

Note that this page has the same page dimensions as the other pages in the document. That means, in a double-sided book, that it's a right-hand page. Thus, you may notice the unequal left and right margins, which might look undesirable, especially if your title is in the center. However, the explanation is simple: this title page is intended to be an inner title, not the cover page. The inner title page is, of course, a right-hand page.

封面是另一回事。这样的页面应该是单面的,因此它的左右页边距应该相等。封面通常作为独立文档制作,单独打印。对于电子文档,您可以使用pdfpages包。请参阅LaTeX Cookbook第 5 章包括图像”中的“包括整个页面”部分或第 8 章“充分利用 PDF”中的合并 PDF 文件部分。

A cover page is a different thing. Such a page should be one-sided, and thus it should have equal left and right margins. A cover page is often produced as a standalone document, printed out separately. For an electronic document, you may use the pdfpages package. Refer to the Including whole pages section in Chapter 5, Including Images, or the Combining PDF files section in Chapter 8, Getting the Most Out of the PDF, in the LaTeX Cookbook.

标题包提供创建复杂标题页的功能要获得有关如何设计标题页的一些想法,您可以查看Peter Wilson 撰写的标题页示例,可从texdoc titlepageshttps://texdoc.org/pkg/titlepages获得。

The titling package offers features to create sophisticated title pages. To get some ideas on how title pages may be designed, you could look at Some Examples of Title Pages, by Peter Wilson, available from texdoc titlepages and at https://texdoc.org/pkg/titlepages.

由文件、标题、扉页和样式设置组成的文档框架称为模板。我们将在下一节中学习如何使用模板。

A document framework consisting of files, headings, title page, and style settings is called a template. We will learn how to use templates in the next section.

使用模板

Working with templates

我们在开发文档时,指定文档类,选择有意义的包和选项,并为内容创建框架。为每个文档重复这些步骤太费力了。

When we develop a document, we specify the document class, choose meaningful packages and options, and create a frame for the content. To repeat these steps for each document would be too laborious.

如果我们计划编写多个相同类型的文档,我们可以创建一个模板。这可能是一个包含以下内容的.tex文件:

If we plan to write several documents of the same type, we may create a template. This could be a .tex file containing the following:

  • 合适的文档类的声明以及一组有意义的选项
  • A declaration of a suitable document class together with a set of meaningful options
  • 常规使用的包裹和最符合我们文件类型的包裹
  • Routinely used packages and packages that are most eligible for our document type
  • 文本页眉、页脚和正文的预定义布局
  • A predefined layout for the header, footer, and body of the text
  • 自制宏方便我们工作
  • Self-made macros to facilitate our work
  • 一个分段命令的框架,我们在其中填写标题和正文
  • A framework of sectioning commands, where we fill in the headings and the body text
  • 或者包含\include\input命令的框架,我们稍后会为其创建正文文本块
  • Or a framework containing \include or \input commands, for which we create the body text chunks later on

随着我们提高我们的 LaTeX 知识,这样的模板可能会增长并变得更好,更多复杂的。许多用户在互联网上发布他们精心制作的模板。许多大学、研究所、期刊和出版商都这样做,为论文、论文、期刊文章和书籍等文档提供模板,以满足他们的要求。

As we improve our LaTeX knowledge, such templates might grow and become better and more sophisticated. Many users publish their elaborate templates on the internet. Many universities, institutes, journals, and publishers do the same, offering templates for documents such as theses, papers, journal articles, and books, meeting their requirements.

您会在模板中找到精心策划的模板集合,这些模板按文档类型排列,例如论文、报告、信件和演示文稿,并附有示例输出画廊在https://latextemplates.com

You will find a carefully curated collection of templates, arranged by document types such as theses, reports, letters, and presentations, accompanied by sample output, in a template gallery at https://latextemplates.com.

您可以下载一个模板并开始填写您的文本。或者,您可以使用编辑器提供的预定义模板开始文档。让我们先试试看。

You may download a template and start to fill in your text. Alternatively, you could start a document with a predefined template offered by your editor. Let's try that first.

LaTeX 编辑器经常提供模板开始。TeXworks 也提供一些。因此,我们将测试此功能。让我们拿一个,打开它,修改它,然后编译它:

LaTeX editors often provide templates to start with. TeXworks offers some as well. So, we will test this feature. Let's take one, open it, modify it, and compile it:

  1. 在 TeXworks 主菜单中,点击File然后点击New from template。将打开一个窗口,允许您选择一个模板:
    图 11.5 – TeXworks 模板选择

    图 11.5 – TeXworks 模板选择

  2. In the TeXworks main menu, click on File and then on New from template. A window will open, allowing you to choose a template:

    Figure 11.5 – TeXworks template selection

  3. 在较低的窗口的一部分,您可以阅读模板的来源。这是 KOMA-Script ( KOMA-letter.tex )的示例:

    % !TEX TS-program = pdflatex

    % !TEX 编码 = UTF-8 Unicode

    % 标准 LaTeX 字母类的替代品。

    \documentclass[fontsize=12pt, paper=a4]{scrlttr2}

    % 不要忘记阅读 KOMA-Script 文档,

    % scrguien.pdf

    \setkomavar{fromname}{} % 你的名字

    \setkomavar{fromaddress}{Address \\ of \\ Sender}

    \setkomavar{signature}{} % 在 \closing 之后打印

    \renewcommand{\raggedsignature}{\raggedright} % 使

    % 签名参差不齐

    \setkomavar{subject}{} % 信件的主题

    \开始{文档}

    \begin{letter}{Name and \\ Address \\ of \\ Recipient}

    \opening{} % 例如。你好

    \closing{} %例如。问候

    \结束{字母}

    \end{文档}

  4. In the lower part of the window, you can read the template's source. Here's an example of KOMA-Script (KOMA-letter.tex):

    % !TEX TS-program = pdflatex

    % !TEX encoding = UTF-8 Unicode

    % An alternative to the standard LaTeX letter class.

    \documentclass[fontsize=12pt, paper=a4]{scrlttr2}

    % Don't forget to read the KOMA-Script documentation,

    % scrguien.pdf

    \setkomavar{fromname}{} % your name

    \setkomavar{fromaddress}{Address \\ of \\ Sender}

    \setkomavar{signature}{} % printed after the \closing

    \renewcommand{\raggedsignature}{\raggedright} % make

    % the signature ragged right

    \setkomavar{subject}{} % subject of the letter

    \begin{document}

    \begin{letter}{Name and \\ Address \\ of \\ Recipient}

    \opening{} % eg. Hello

    \closing{} %eg. Regards

    \end{letter}

    \end{document}

  5. 单击打开。填补空白并编辑填充物示例文本:

    \documentclass[fontsize=12pt, paper=a4]{scrlttr2}

    \setkomavar{fromname}{我的名字} % 你的名字

    \setkomavar{fromaddress}{街道,城市}

    \setkomavar{signature}{Name} % 在 \closing 之后打印

    \setkomavar{subject}{Invoice 1/2021} % 信件的主题

    \setkomavar{地点}{地点}

    \setkomavar{日期}{2021 年 1 月 1 日}

    \开始{文档}

    \begin{letter}{Customer Name\\ Street No. X \\ City \\ Zipcode}

      \opening{它可能与谁有关} % 例如。你好

      文本在 \ldots 之后

      \bigskip

      \closing{谨致问候} %eg。问候

    \结束{字母}

    \end{文档}

  6. Click on Open. Fill in the gaps and edit the filler text of the example:

    \documentclass[fontsize=12pt, paper=a4]{scrlttr2}

    \setkomavar{fromname}{My name} % your name

    \setkomavar{fromaddress}{Street, City}

    \setkomavar{signature}{Name} % printed after the \closing

    \setkomavar{subject}{Invoice 1/2021} % subject of the letter

    \setkomavar{place}{Place}

    \setkomavar{date}{January 1, 2021}

    \begin{document}

    \begin{letter}{Customer Name\\ Street No. X \\ City \\ Zipcode}

      \opening{To whom it may concern} % eg. Hello

      Text follows \ldots

      \bigskip

      \closing{With kind regards} %eg. Regards

    \end{letter}

    \end{document}

  7. 编译文档。看看我们的测试信:
  8. Compile the document. Have a look at our test letter:
图 11.6 – 一封信件文件

图 11.6 – 一封信件文件

Figure 11.6 – A letter document

那很简单!我们刚刚打开模板并修改了填充文本。通过阅读 KOMA-Script文档,我们可以了解到\setkomavar命令用于指定模板参数的值,例如nameaddresssubject。我们也用它来声明日期地点。

That was easy! We just opened the template and modified the filler text. By reading the KOMA-Script documentation, we can learn that the \setkomavar command is for specifying values for template parameters such as name, address, and subject. We used that to declare date and place as well.

一旦我们将我们的个人数据写入此模板,我们可以将其保存以备后用,而不是为每个字母输入我们的地址。

Once we have written our personal data into this template, we may save that for later use instead of typing our address for each letter.

KOMA-Script 文档 ( texdoc scrguien ) 很好地描述了这个字母类的特性。使用它,您将能够创建具有专业外观的商业信函模板。

The KOMA-Script documentation (texdoc scrguien) describes the features of this letter class well. Using this, you would be able to create your professional-looking letter template for business use.

想象一下,将使用 LaTeX 布局和字体创建的求职信与缩微字体包放在使用其他文字处理软件制作的求职信旁边。哪个会给人留下更好的印象?

Imagine putting a job application letter created with the LaTeX layout and fonts together with the microtype package next to an application letter produced with some other word processing software. Which one will create a better impression?

在 Internet 上查找 LaTeX 模板、代码和提示时,您会发现大量信息和代码。此代码可能已过时,并且此信息可能已过时。

While looking for LaTeX templates, code, and tips on the internet, you will find a lot of information and code. This code might be outdated, and this information might be obsolete.

当您开发自己的模板时,您可能希望确保使用当今可用的最佳包、选项和解决方案。你怎么能确定?

When you develop your own template, you would probably like to be sure to use the best packages, options, and solutions available today. How can you be sure?

这两个问题都可以通过研究l2tabu来回答。这是An essential guide to LaTeX2e usage的常用快捷方式,该文档专注于过时的命令和包,展示了 LaTeX 用户容易犯的最常见和最严重的错误。由于 LaTeX 已经发展多年,一些包和技术仍然可用并在在线资源中有所描述,但它们可能不再值得推荐。阅读本指南。它将帮助您评估在 Internet 上找到的模板和代码,并确保您自己生成最佳代码。

Both questions can be answered by studying l2tabu. This is the common shortcut for An essential guide to LaTeX2e usage, a document focusing on obsolete commands and packages, demonstrating the most common and severe mistakes that LaTeX users tend to make. As LaTeX has developed over many years, some packages and techniques are still available and described in online resources, but they may no longer be recommendable. Read this guide. It will help you to evaluate templates and code found on the internet, and ensure that you produce optimal code yourself.

只需在命令提示符下键入texdoc l2tabuen或访问https://texdoc.org/pkg/l2tabuen

Just type texdoc l2tabuen at the command prompt or visit https://texdoc.org/pkg/l2tabuen.

要测试模板,您可以使用blindtext包及其命令\blindtext\Blinddocument\blindtext命令生成一段虚拟文本,而\Blinddocument命令为大文档生成虚拟内容,包括部分和列表。这将展示模板的输出质量。使用这个包时,我们应该加载带有语言选项的babel包,例如,只需要一个基本的最小文章模板:

To test a template, you may use the blindtext package and its commands, \blindtext and \Blinddocument. The \blindtext command generates a paragraph of dummy text, and the \Blinddocument command generates dummy content for a big document, including sections and lists. That will demonstrate the output quality of a template. When using this package, we should load the babel package with a language option, for example, just with a basic minimal article template:

\文档类{文章}

\documentclass{article}

\usepackage[english]{babel}

\usepackage[english]{babel}

\usepackage{盲文}

\usepackage{blindtext}

\开始{文档}

\begin{document}

\开始{摘要}

\begin{abstract}

\盲文

\blindtext

\结束{摘要}

\end{abstract}

\盲文

\Blinddocument

\end{文档}

\end{document}

这给了我们一个这样开头的文档:

That gives us a document starting like this:

图 11.7 – 一篇带有虚拟文本的文章

图 11.7 – 一篇带有虚拟文本的文章

Figure 11.7 – An article with dummy text

如果你像我们一样使用 TeXworks在前面的例子中做了,你可以从一些现成的模板中选择或从https://latextemplates.com下载模板。但是,如果你使用https://overleaf.com在线工作,您有更多选择。基本上,您可以单击“新建项目”并选择几个基本模板之一:

If you use TeXworks, as we did in the previous example, you can choose from some ready-to-use templates or download a template from https://latextemplates.com. However, if you work online with https://overleaf.com, you have even more choices. Basically, you can click on New Project and choose one of several basic templates:

图片 11.8 – 在 Overleaf 中打开一个模板

图片 11.8 – 在 Overleaf 中打开一个模板

Figure 11.8 – Opening a template in Overleaf

如果您点击查看全部,您可以浏览综合目录:

If you click on View All, you can browse a comprehensive catalog:

图 11.9 – Overleaf 模板目录

图 11.9 – Overleaf 模板目录

Figure 11.9 – The Overleaf template catalog

Overleaf 模板集合包含数千个可用于填充文本的模板。他们中的很多由机构和用户贡献。质量可能会有所不同,但您可以在浏览时看到内容或标题的屏幕截图,并亲自试用这些模板。

The Overleaf template collection contains several thousand templates ready to use for filling in your text. A lot of them are contributed by institutions and users. Quality may vary, but you can see screenshots of contents or titles while browsing and try out those templates yourself.

我们可以在搜索栏中输入关键字,例如文档类型、大学或学院名称、功能或包名称。

We can enter keywords such as the document type, university or college name, features, or package names in the Search bar.

我们可以点击Open as Template然后获取带有一些填充文本的可编译文档。这使我们能够在大约 10 分钟内试用 10 个模板,直到找到最适合我们的模板。

We can click on Open as Template and will get a compilable document with some filler text. That allows us to try out 10 templates in around 10 minutes until we find the perfect one for us.

概括

Summary

我们在本章中学到的技术将帮助我们开发和维护更大的项目。尽管狂热的用户更喜欢 LaTeX 来编写小文档,但许多人学习 LaTeX 是因为他们打算编写较长的文本,例如论文。但是,拆分文档和使用模板也适用于小段文字,例如信件——只要想想页眉、页脚和地址字段即可。

The techniques we learned in this chapter will help us to develop and maintain bigger projects. Though enthusiastic users prefer LaTeX to write small documents, many people learn LaTeX because they plan to write longer texts such as a thesis. However, splitting documents and the use of templates are useful for small pieces of writing as well, such as for letters—just think of the header, footer, and address fields.

在本章中,我们创建并管理了由多个文件组成的大型文档,包括封面和封底以及单独的扉页。

In this chapter, we created and managed large documents consisting of several files, including front and back matter and a separate title page.

现在我们可以开发和处理大型文档,我们将在下一章中看到如何进一步改进它们。

Now that we can develop and handle large documents, we will see how to improve them further in the next chapter.

第 12 章:进一步增强文档

Chapter 12: Enhancing Your Documents Further

到目前为止,您已经能够以良好的印刷质量编写结构化文档,并且可以满足对书籍、期刊文章或大学论文等经典出版物的高期望。

By now, you're capable of writing structured documents in fine typographical quality, and you can meet high expectations for classic publications such as books, journal articles, or a university thesis.

也许您想在线发布您的 PDF 文档。此类电子文档或电子书通常需要导航,例如超链接和书签索引。

Perhaps you would like to publish your PDF documents online. Such electronic documents or e-books usually require navigation such as hyperlinks and a bookmark index.

本章将为我们提供此类增强的工具。我们将弄清楚如何执行以下操作:

This chapter shall provide us with the tools for such enhancements. We shall figure out how to perform the following:

  • 使用超链接和书签
  • Using hyperlinks and bookmarks
  • 设计标题
  • Designing headings
  • 给我们的文件上色
  • Coloring our documents

让我们使用专用于这些主题的 LaTeX 包来实现这一点。

Let's implement this by using LaTeX packages that are dedicated to these subjects.

技术要求

Technical requirements

您可以使用本地 LaTeX 安装,也可以在https://latexguide.org/chapter-12在线编译示例代码。

You can use a local LaTeX installation, or you can compile the example code online at https://latexguide.org/chapter-12.

该代码可在 GitHub 上找到:https://github.com/PacktPublishing/LaTeX-Beginner-s-Guide-Second-Edition/tree/main/Chapter_12_-_Enhancing_Your_Documents_Further

The code is available on GitHub: https://github.com/PacktPublishing/LaTeX-Beginner-s-Guide-Second-Edition/tree/main/Chapter_12_-_Enhancing_Your_Documents_Further.

在本章中,我们将使用以下包:bmcolortblhyperreftitlesecxcolor。由于我们将继续使用前一章的代码,因此我们需要与第 11 章开发大型文档中相同的包。

In this chapter, we will use the following packages: bm, colortbl, hyperref, titlesec, and xcolor. Since we're going to continue working with the code of the previous chapter, we require the same packages as in Chapter 11, Developing Large Documents.

我们还将简要地看一下书签包。

We will also briefly look at the bookmark package.

使用超链接和书签

Using hyperlinks and bookmarks

有一个复杂的称为hyperref 的包,它自动执行几乎所有基本的超链接。让我们来看看。

There's a sophisticated package called hyperref that does nearly all basic hyperlinking automatically. Let's check it out.

添加超链接

Adding hyperlinks

我们应该加载hyperref包并检查其效果:

We shall load the hyperref package and inspect its effect:

  1. 打开我们在上一章中使用的preamble.tex文件。最后,添加这一行:

    \usepackage{hyperref}

  2. Open the preamble.tex file, which we used in the previous chapter. At the end, add this line:

    \usepackage{hyperref}

  3. 以相同的名称保存此文档。
  4. Save this document under the same name.
  5. 打开我们上一章的方程式书;我们称之为equations.tex
  6. Open our Book of Equations from the previous chapter; we called it equations.tex.
  7. 在不做任何更改的情况下编译文档两次。让我们看看文档现在如何显示;在这里,我们可以看到指示超链接的红色框:
  8. Compile the document twice without making any changes. Let's see how the document now appears; here, we can see red boxes indicating hyperlinks:
图 12.1 – 带有超链接和书签的目录

图 12.1 – 带有超链接和书签的目录

Figure 12.1 – A table of contents with hyperlinks and bookmarks

交叉引用,例如作为方程式编号的参考,也有红色框:

Cross-references, such as references to equation numbers, also have red boxes:

图 12.2 – 对带有超链接的方程式的引用

图 12.2 – 对带有超链接的方程式的引用

Figure 12.2 – References to equations with hyperlinks

通过只是加载hyperref包,我们的文档发生了显着变化:

By just loading the hyperref package, our document has significantly changed:

  • 我们有一个书签栏,它使我们可以轻松地浏览文档。
  • We got a Bookmarks bar, which allows us to navigate through the document easily.
  • 目录中的每个条目都已成为相应章节开头的超链接。超链接用红色边框突出显示。
  • Each entry in the table of contents has become a hyperlink to the beginning of the corresponding chapter. Hyperlinks are highlighted by red borders.
  • 所有交叉引用都变成了超链接。
  • All cross-references have become hyperlinks.

这是对我们文档的电子版本的极大改进。

This is an excellent improvement for electronic versions of our documents.

当我们打印文档时,红框不会出现在纸上;它们仅用于电子导航。这同样适用于书签。

The red boxes will not appear on paper when we print the document; they are only for electronic navigation. The same applies to the bookmarks.

如果你不就像带有红色边框的超链接的默认外观一样,可以通过编辑hyperref的选项轻松更改。让我们接下来试试这个。

If you don't like the default appearance of the hyperlinks with red borders, it can easily be changed by editing the options to hyperref. Let's try this next.

自定义超链接

Customizing hyperlinks

在这里,我们要将选项传递给hyperref影响它强调超链接的方式:

Here, we shall pass options to hyperref affecting the way it emphasizes hyperlinks:

  1. 再次打开preamble.tex文件。这次,指定hyperref的选项:

    \usepackage[colorlinks=true,linkcolor=red]{hyperref}

  2. Open the preamble.tex file again. This time, specify the options for hyperref:

    \usepackage[colorlinks=true,linkcolor=red]{hyperref}

  3. 保存这个文件,转到主equations.tex文件,编译两次。目录已更改:
  4. Save this document, go to the main equations.tex document, and compile it twice. The table of contents has changed:
图 12.3 – 带有彩色超链接的目录

图 12.3 – 带有彩色超链接的目录

Figure 12.3 – Table of contents with colored hyperlinks

代替框架,我们现在有一个红色来强调超链接。与盒子不同,我们可以在打印文档中看到颜色。

Instead of frames, we now have a red color for emphasized hyperlinks. Unlike the boxes, we can see the color in a printed document.

hyperref提供了设置这些选项的方法。我们使用的第一个如下:

hyperref offers ways to set up these options. The first one we used is the following:

\usepackage[键=值列表]{hyperref}

\usepackage[key=value list]{hyperref}

或者,我们可以只写\usepackage{hyperref}然后设置选项:

Alternatively, we could just write \usepackage{hyperref} and set the options afterward:

\hypersetup{键=值列表}

\hypersetup{key=value list}

我们的示例将对以下内容执行相同的操作:

Our example would do the same with the following:

\hypersetup{colorlinks=true,linkcolor=red}

\hypersetup{colorlinks=true,linkcolor=red}

我们也可以结合这些方法。

We can also combine these methods.

我们将查看一些特别有用的选项。对于以下选项,您可以选择truefalse。如果不指定,hyperref会选择默认值,此处显示在括号中:

We will look at a selection of particularly useful options. For the following options, you can choose either true or false. If you don't specify, hyperref selects the default value, which is shown in parentheses here:

  • draft:关闭所有超文本选项 ( false )。
  • draft: Turns all hypertext options off (false).
  • final:打开所有超文本选项 ( true )。
  • final: Turns all hypertext options on (true).
  • debug : 额外打印将诊断消息写入日志文件 ( false )。
  • debug: Prints extra diagnostic messages into the log file (false).
  • backref:向参考书目添加反向链接,即从参考书目项目返回到文本中的引文的链接(false)。
  • backref: Adds backlinks to the bibliography, that is, links from bibliography items back to citations in the text (false).
  • hyperindex:在索引中添加指向页码的链接 ( true )。
  • hyperindex: Adds links to page numbers in the index (true).
  • hyperfootnotes:将脚注标记转换为超链接 ( true )。
  • hyperfootnotes: Converts footnote markers into hyperlinks (true).
  • hyperfigures:为图形添加超链接 ( false )。
  • hyperfigures: Adds hyperlinks to figures (false).
  • 链接页面:在目录( TOC )图表列表( LOF ) 和表格列表( LOT )、hyperrefs添加链接到页码而不是文本 ( false )。
  • linktocpage: In the table of contents (TOC), list of figures (LOF) and list of tables (LOT), hyperrefs adds links to page numbers instead of to the text (false).
  • frenchlinks:对链接使用小型大写字母而不是颜色 ( false )。
  • frenchlinks: Uses small caps for links instead of color (false).
  • bookmarks:为 PDF 阅读器导航写入书签 ( true )。
  • bookmarks: Writes bookmarks for the PDF reader navigation (true).
  • bookmarksopen:打开 PDF 时在展开视图中显示所有书签 ( false )。
  • bookmarksopen: Shows all bookmarks in an expanded view when the PDF is opened (false).
  • bookmarksnumbered:包括书签中的节号 (false)。
  • bookmarksnumbered: Includes the section number in bookmarks (false).
  • colorlinks:根据链接的类型,例如页面引用、URL、文件引用和引用,用颜色编写链接和锚点,而不是在链接周围打印边框 (false)。
  • colorlinks: Writes links and anchors in color, depending on the type of link, such as page references, URLs, file references, and citations, instead of printing a border around links (false).

当您使用colorlinks选项时,您可以根据链接类型选择您想要的颜色,如下表所示。同样,默认值在括号中:

When you use the colorlinks option, you can choose the color you want by link type, as in the following list. Again, the default value is in parentheses:

  • linkcolor:一般链接的颜色(红色
  • linkcolor: Color of general links (red)
  • citecolor:参考书目项目的引文颜色(绿色
  • citecolor: Color for citations of bibliography items (green)
  • urlcolor : 网站地址的颜色,即 URLs ( magenta )
  • urlcolor: Color for website addresses, that is, URLs (magenta)
  • filecolor:文件链接的颜色(青色
  • filecolor: Color for links to files (cyan)

更多用于自定义链接边框、PDF 页面大小、锚点、书签外观和 PDF 页面显示样式的选项。hyperref文档列出所有这些。只需在命令行输入texdoc hyperref或访问https://texdoc.org/pkg/hyperref

There are many more options for customizing link borders, the PDF page size, anchors, bookmark appearance, and the PDF page display style. The hyperref documentation lists them all. Just type texdoc hyperref at the command line or visit https://texdoc.org/pkg/hyperref.

隐藏链接

Hiding links

如果您想禁用所有链接突出显示,例如在纸上打印,只需给hidelinks选项不赋值即可。然后,没有边框和颜色的链接将是不可见的,就像普通文本一样。

If you want to disable all link highlighting, such as for printing on paper, just give the hidelinks option without value. Then, links will be invisible without a border and color, like regular text.

一些文本选项允许我们指定 PDF 文件的元数据,例如作者姓名、标题和关键字。如果您使用 PDF 阅读器检查文档属性,您可以看到此信息。这更加有益,因为互联网搜索引擎可以根据此元信息查找和分类您的 PDF 文档。如果您在 Internet 上发布,这会提高读者找到您的出版物的机会。

Some text options allow us to specify the metadata of PDF files, such as the author's name, title, and keywords. You can see this information if you inspect the document properties with the PDF reader. This is even more beneficial as internet search engines can find and classify your PDF document according to this meta information. If you publish on the internet, this improves the chances of readers finding your publication.

这就是为什么我们现在要将 PDF 元数据添加到第 11 章开发大型文档”中的方程式书。除了选择合理的关键字外,我们还将设置标题和作者姓名。在开发过程中,为什么不选择我们将本书献给的伟大数学家呢?那么,让我们这样做:

That's why we will now add PDF metadata to our Book of Equations from Chapter 11, Developing Large Documents. Besides choosing sensible keywords, we will set the title and the author's name. During development, why not choose the great mathematician to whom we dedicated our book? So, let's do it:

  1. 打开preamble.tex文件并添加以下行:

    \hypersetup{pdfauthor={卡尔·弗里德里希·高斯},

      pdftitle={方程式大书},

      pdfsubject={求解方程和方程组},

      pdfkeywords={方程式,数学}}

  2. Open the preamble.tex file and add the following lines:

    \hypersetup{pdfauthor={Carl Friedrich Gauss},

      pdftitle={The Big Book of Equations},

      pdfsubject={Solving Equations and Equation Systems},

      pdfkeywords={equations,mathematics}}

  3. 保存该文件。转到主equations.tex文档并单击Typeset进行编译。
  4. Save that file. Go to the main equations.tex document and click on Typeset to compile.
  5. 让我们检查文档属性。因此,如果您使用的是 Acrobat Reader,请单击文件菜单,然后在属性上
  6. Let's inspect the Document Properties. So, if you are using Acrobat Reader, click on the File menu and then on Properties:
图 12.4 – 文档属性中的 PDF 元数据

图 12.4 – 文档属性中的 PDF 元数据

Figure 12.4 – PDF metadata in document properties

那很简单。我们使用hyperref选项提供了所有文档属性;我们只需要用大括号将每个条目括起来。

That was easy. We provided all the document properties using hyperref options; we just had to enclose each entry in curly braces.

最常用的元信息选项如下:

The most used meta information options are as follows:

  • pdftitle : 设置标题
  • pdftitle: Sets the title
  • pdfauthor : 设置作者
  • pdfauthor: Sets the author
  • pdfsubject:设置主题
  • pdfsubject: Sets the subject
  • pdfcreator : 设置创建者
  • pdfcreator: Sets the creator
  • pdfproducer : 设置生产者
  • pdfproducer: Sets the producer
  • pdfkeywords:设置关键字
  • pdfkeywords: Sets keywords

由于hyperref重新定义许多其他包的命令来添加超链接功能,我们必须在这些包之后加载它。

As hyperref redefines many other packages' commands to add hyperlink functionality, we have to load it after those packages.

hyperref 加载顺序

hyperref loading order

一个好的经验法则是将hyperref包加载为序言中的最后一个包。一些包是该规则的例外;即,algorithmamsrefsbookmarkchappgcleverefglossarieshypernatlinguexsidecaptabularx已知是例外。有关详细信息,请参阅https://latexguide.org/hyperref

A good rule of thumb is to load the hyperref package as the last package in your preamble. A few packages are exceptions to that rule; namely, algorithm, amsrefs, bookmark, chappg, cleveref, glossaries, hypernat, linguex, sidecap, and tabularx are known to be exceptions. For more information, see https://latexguide.org/hyperref.

我们现在将看到添加超链接和书签的更多方法。

There are further ways of adding hyperlinks and bookmarks that we will now see.

手动创建超链接

Creating hyperlinks manually

作为hyperref已经为几乎所有类型的参考创建链接,很少需要自己创建链接。但当然,这是可能的。hyperref为此提供了用户命令:

As hyperref already creates links for nearly all kinds of references, it's rarely necessary to create links by yourself. But of course, it's possible. hyperref provides user commands for that:

  • \href{URL}{text}将文本转换为指向 URL(网站地址)的超链接。
  • \href{URL}{text} turns text into a hyperlink that points to the URL, the website address.
  • \url{URL}打印 URL 并链接它。
  • \url{URL} prints the URL and links it.
  • \nolinkurl{URL}打印 URL 而不链接它。
  • \nolinkurl{URL} prints the URL without linking it.
  • \hyperref{label}{text}将文本更改为一个超链接,该超链接链接到已设置标签的位置,因此指向相同的位置\ref{label}将指向。
  • \hyperref{label}{text} changes the text into a hyperlink that links to the place where the label has been set, thus to the same place \ref{label} would point to.
  • \hypertarget{name}{text}为以文本为锚点的潜在超链接创建目标名称
  • \hypertarget{name}{text} creates a target name for potential hyperlinks with text as the anchor.
  • \hyperlink{name}{text}文本变成指向目标name 的超链接。
  • \hyperlink{name}{text} turns text into a hyperlink that points to the target name.

有时您可能只需要一个锚点,例如,如果您使用\addcontentsline,它会创建一个超链接目录条目,但还没有设置锚点的分段命令。TOC 条目将指向先前设置的锚点,因此到错误的地方。

Sometimes you might just need an anchor, for instance, if you use \addcontentsline, which creates a hyperlinked TOC entry, but there hasn't been a sectioning command setting the anchor. The TOC entry would point to the previously set anchor, thus to the wrong place.

\phantomsection命令来拯救; 它只是像\hypertarget{}{}那样设置一个锚点。它主要用于在链接到正确页面的同时为参考书目创建 TOC 条目,如下所示:

The \phantomsection command comes to the rescue; it just sets an anchor like \hypertarget{}{} would do. It's mostly used this way for creating a TOC entry for the bibliography while linking to the correct page, as follows:

\cleardoublepage

\cleardoublepage

\phantomsection

\phantomsection

\addcontentsline{toc}{chapter}{\bibname}

\addcontentsline{toc}{chapter}{\bibname}

\书目{名称}

\bibliography{name}

因此,我们可以将\phantomsection视为一个不可见的\section锚点。随后的\addcontentsline命令引用该锚点。

So, we may consider \phantomsection as an invisible \section anchor. The following \addcontentsline command then refers to that anchor.

手动创建书签

Creating bookmarks manually

你的书签面板可能已经充满了章节和部分条目。但是如果你想自己添加书签怎么办?您可以按如下方式进行。

Your bookmarks panel might already be full of chapters and section entries. But what if you wish to add bookmarks by yourself? You can do that as follows.

\pdfbookmark[level]{text}{name}创建一个带有可选指定级别文本的书签。默认级别为0。像使用\label命令一样处理名称;它应该是唯一的,因为它代表内部锚点。

\pdfbookmark[level]{text}{name} creates a bookmark with text at the optionally specified level. The default level is 0. Treat name just like with the \label command; it should be unique because it stands for the internal anchor.

您还可以创建相对于当前级别的书签:

You can also create bookmarks relative to the current level:

  • \currentpdfbookmark{text}{name}在当前层放置一个书签。
  • \currentpdfbookmark{text}{name} puts a bookmark at the current level.
  • \belowpdfbookmark{text}{name}创建更深一层的书签。
  • \belowpdfbookmark{text}{name} creates a bookmark one level deeper.
  • \subpdfbookmark{text}{name}增加级别并在更深的级别创建书签。
  • \subpdfbookmark{text}{name} increases the level and creates a bookmark at that deeper level.

书签包提供了更多自定义书签的功能,例如选择字体样式和颜色您可以通过命令行或在https://texdoc.org/pkg/bookmark

The bookmark package offers more features for customizing bookmarks, such as choosing the font style and color. You can read about it by running texdoc bookmark at the command line or at https://texdoc.org/pkg/bookmark.

在书签中使用数学公式和特殊符号

Using math formulas and special symbols in bookmarks

由于PDF限制,我们不能在 PDF 书签中使用数学和特殊符号。这可能会导致问题,例如,在标题或字体命令中带有数学符号的分段命令中,这些命令将传递给书签。不过,有一个解决方案,那就是这个命令:

Due to PDF restrictions, we cannot use math and special symbols within PDF bookmarks. This might cause a problem, for instance, in sectioning commands with math symbols in their title or font commands, which would be passed to the bookmark. There's a solution, though, and that's this command:

\texorpdfstring{带有 TeX 代码的字符串}{pdf 文本字符串}

\texorpdfstring{string with TeX code}{pdf text string}

它根据上下文返回参数以避免此类问题。它可以这样使用:

It returns the argument depending on the context to avoid such problems. It can be used like this:

\section{方程

\section{The equation

  \texorpdfstring{$y=x^2$}{y=x\texttwosuperior}}

  \texorpdfstring{$y=x^2$}{y=x\texttwosuperior}}

这可能会派上用场。

That may come in handy.

如果使用unicode选项加载hyperref,则可以在书签中使用 Unicode 文本字符,例如:

If you load hyperref with the unicode option, you could use Unicode text characters in bookmarks, such as here:

\section{\texorpdfstring{$\gamma$}{\textgamma} 辐射}

\section{\texorpdfstring{$\gamma$}{\textgamma} radiation}

让我们在一个小示例文档中快速了解这些命令是如何工作的。它是这样的:

Let's quickly see how these commands work in a small sample document. Here it goes:

\文档类{文章}

\documentclass{article}

\使用包{bm}

\usepackage{bm}

\usepackage[colorlinks=true,psdextra,unicode]{hyperref}

\usepackage[colorlinks=true,psdextra,unicode]{hyperref}

\开始{文档}

\begin{document}

\pdfbookmark[1]{\contentsname}{toc}

\pdfbookmark[1]{\contentsname}{toc}

\目录

\tableofcontents

\pdfbookmark[1]{摘要}{摘要}

\pdfbookmark[1]{Abstract}{abstract}

\开始{摘要}

\begin{abstract}

\定心

\centering

示例部分如下。

Sample sections follow.

\结束{摘要}

\end{abstract}

\section{方程

\section{The equation

  \texorpdfstring{$y=x^2$}{y=x\texttwosuperior}}

  \texorpdfstring{$y=x^2$}{y=x\texttwosuperior}}

\section{\texorpdfstring{$\gamma$}{\textgamma} 辐射}

\section{\texorpdfstring{$\gamma$}{\textgamma} radiation}

\section[\texorpdfstring{令 $\int\sim\sum$ 为

\section[\texorpdfstring{Let $\int\sim\sum$ for

  $n\rightarrow\infty$}

  $n\rightarrow\infty$}

  {让 \int\sim\sum\ 为 n\rightarrow\infty}]

  {Let \int\sim\sum\ for n\rightarrow\infty}]

  {令 $\bm{\int\sim\sum}$ 为 $\bm{n\rightarrow\infty}$}

  {Let $\bm{\int\sim\sum}$ for $\bm{n\rightarrow\infty}$}

\end{文档}

\end{document}

作为突出显示在前面的代码中, \section命令做了这三件事:

As highlighted in the preceding code, the \section command does these three things:

  • 它打印节标题。这一次,我们使用bm包中的\bm命令来获得粗体数学字体。将其与其他标题进行比较。
  • It prints the section heading. This time, we used the \bm command from the bm package to get a bold math font. Compare it with the other headings.
  • 它将节名称放入目录中。
  • It puts the section name into the table of contents.
  • 它使用 Unicode 文本符号创建一个书签作为数学符号的替代品。我们使用unicode选项和psdextra选项加载hyperref,这允许书签中的数学符号。
  • It creates a bookmark with Unicode text symbols as replacements for math symbols. We loaded hyperref with the unicode option and the psdextra option, which allows math symbols in bookmarks.

我们得到此输出带有书签:

We get this output with bookmarks:

图 12.5 – 书签中的数学公式

图 12.5 – 书签中的数学公式

Figure 12.5 – Math formulas in bookmarks

笔记

Note

在\texorpdfstring的第一个参数中,我们使用$ ... $作为数学模式。然而,在\texorpdfstring的第二个参数中,我们故意省略了$ ... $因为那将是 Unicode 文本,而不是数学字体字形。

In the first argument to \texorpdfstring, we used $...$ for the math mode. However, in the second argument to \texorpdfstring, we omitted $...$ intentionally since that will be Unicode text, not math font glyphs.

虽然标题和书签中的数学公式可能无论如何都不是一个好主意,但我们发现如果我们真的需要它,我们有办法完成它。

While math formulas in headings and bookmarks may not be a good idea anyway, we see that we have ways to get it done if we really need it.

在下一节中,我们将处理标题的外观。

In the next section, we will deal with the appearance of headings.

设计标题

Designing headings

第 2 章格式化文本和创建宏中,我们遇到了以下问题自定义标题。必须有一种一致的方法来修改整个文档的标题字体、间距和编号。幸运的是,有一个方便的包,叫做titlesec。我们现在将使用它来设计章节和章节标题。

In Chapter 2, Formatting Text and Creating Macros, we encountered the problem of customizing headings. There has to be a consistent way to modify the font of headings, their spacing, and their numbering for the whole document. Fortunately, there's a handy package for that, and it's called titlesec. We shall use it now to design chapter and section headings.

我们将回到本章中使用的示例。我们的目标是创建具有这种外观的标题:

We'll return to the example that we used in this chapter. Our goal is to create headings with this appearance:

  • 居中标题
  • Centered titles
  • 较小的字体大小
  • Smaller font size
  • 上下空间更少
  • Less space above and below
  • 使用无衬线字体,这是粗体标题的不错选择
  • With a sans serif font, which is a good choice for bold headings

开始吧:

Let's start:

  1. 打开我们已经在本章中使用过的preamble.tex文件。插入此行以加载titlesec包:

    \usepackage{titlesec}

  2. Open the preamble.tex file, which we have already used in this chapter. Insert this line to load the titlesec package:

    \usepackage{titlesec}

  3. 添加此命令以指定章节标题的布局和字体:

    \titleformat{\chapter}[显示]

      {\normalfont\sffamily\Large\bfseries\centering}

      {\chaptertitlename\ \thechapter}{0pt}{\Huge}

  4. Add this command to specify the layout and font of the chapter headings:

    \titleformat{\chapter}[display]

      {\normalfont\sffamily\Large\bfseries\centering}

      {\chaptertitlename\ \thechapter}{0pt}{\Huge}

  5. 现在,通过再次调用\titleformat命令来定义节标题:

    \titleformat{\section}

      {\normalfont\sffamily\large\bfseries\centering}

      {\thesection}{1em}{}

  6. Now, define the section heading by calling the \titleformat command again:

    \titleformat{\section}

      {\normalfont\sffamily\large\bfseries\centering}

      {\thesection}{1em}{}

  7. 添加此行以调整章节标题的间距:

    \titlespacing*{\chapter}{0pt}{30pt}{20pt}

  8. Add this line to adjust the chapter heading's spacing:

    \titlespacing*{\chapter}{0pt}{30pt}{20pt}

  9. 保存preamble.tex并编译主equation.tex文件。让我们看看标题是如何变化的:
  10. Save preamble.tex and compile the main equation.tex document. Let's see how the headings have changed:
图 12.6 – 居中标题

图 12.6 – 居中标题

Figure 12.6 – Centered headings

第 1 步中,我们加载了titlesec包,它提供了一个全面的界面,用于自定义部分、章节、部分甚至更小的部分的标题,直至子段落。

In step 1, we loaded the titlesec package, which provides a comprehensive interface for customizing headings of parts, chapters, sections, and even smaller sectioning parts down to subparagraphs.

步骤 2中,我们选择了一种显示样式,这意味着编号和实际标题使用单独的行。首先,为了安全起见,我们使用\normalfont切换到基本字体。使用\sffamily,我们切换到无衬线字体,选择大小和粗细,最后声明整个标题应居中。

In step 2, we chose a display style, which means that numbering and the actual title use separate lines. Firstly, we used \normalfont to switch to the base font, to be on the safe side. With \sffamily, we switched to a sans serif font, chose the size and weight, and finally, declared that the complete heading shall be centered.

步骤 3中,一切都与步骤 2非常相似;我们只是省略了[display]以获得同一行的数字和标题。

In step 3, everything is very similar to step 2; we just omitted [display] to get the number and title on the same line.

要了解其余参数,请查看\titleformat定义:

To understand the remaining arguments, have a look at the \titleformat definition:

\titleformat{cmd}[shape]{format}{label}{sep}{before}[after]

\titleformat{cmd}[shape]{format}{label}{sep}{before}[after]

参数的含义如下:

The meaning of the arguments is as follows:

  • cmd代表我们重新定义的分节命令,即\part\chapter\section\subsection\subsubsection\paragraph\subparagraph
  • cmd stands for the sectioning command that we redefine, that is, \part, \chapter, \section, \subsection, \subsubsection, \paragraph, or \subparagraph.
  • shape指定段落形状。可能值的影响如下:

    - display将标签放入一个单独的段落中。

    - hang像在标准部分中一样创建一个悬挂标签,并且是默认选项。

    -运行产生默认情况下,像\paragraph这样的运行标题。

    - leftmargin将标题设置为左边距。

    - rightmargin将标题放在右边距中。

    - drop将文本环绕在标题周围,需要注意避免重叠。

    - wrap与 drop 类似,但会调整标题的空间以匹配最长的文本行。

    -框架像显示一样工作,另外框架标题。

  • shape specifies the paragraph shape. The effects of the possible values are as follows:

    - display puts the label into a separate paragraph.

    - hang creates a hanging label like in standard sections and is the default option.

    - runin produces a run-in title like \paragraph does by default.

    - leftmargin sets the title into the left margin.

    - rightmargin puts the title into the right margin.

    - drop wraps the text around the title, requires care to avoid overlapping.

    - wrap works like drop but adjusts the space for the title to match the longest text line.

    - frame works like display and additionally frames the title.

  • format可能包含将应用于标题的标签和文本的命令。
  • format may contain commands that will be applied to the label and text of the title.
  • label打印标签,即数字。
  • label prints the label, that is, the number.
  • sep是一个长度,指定标签和标题文本之间的分隔。对于显示选项,它是垂直分隔。使用frame选项,它表示文本和框架之间的距离。否则,它是标签和标题之间的水平分隔。
  • sep is a length that specifies the separation between the label and title text. With the display option, it's the vertical separation. With the frame option, it means the distance between the text and the frame. Otherwise, it's the horizontal separation between the label and title.
  • before可以包含标题正文之前的代码。最后一个命令可以带一个参数,该参数应该是标题文本。
  • before can contain code that comes before the title body. The last command is allowed to take an argument, which should then be the title text.
  • after可以包含标题正文之后的代码。
  • after can contain code that comes after the title body.

那有很多选择。查看titlesec文档以通过运行texdoc titlesec或访问https://texdoc.org/pkg/titlesec了解更多信息。

That's a lot of options. Have a look at the titlesec documentation to learn even more by running texdoc titlesec or visiting https://texdoc.org/pkg/titlesec.

我们使用了titlesec命令\chaptertitlename,默认情况下是\chaptername。因此,它默认为Chapter。在附录中,它更改为\appendixname

We used the titlesec command \chaptertitlename, which is \chaptername by default. So, it defaults to Chapter. In an appendix, it changes to \appendixname.

使用以下命令,我们自定义了所有章节标题的间距:

With the following command, we customized the spacing of all chapter headings:

\titlespacing*{cmd}{left}{beforesep}{aftersep}[右]

\titlespacing*{cmd}{left}{beforesep}{aftersep}[right]

论点具有以下含义:

The arguments have the following meanings:

  • left根据所选形状的不同而有所不同:对于dropleftmarginrightmargin,它是标题宽度。使用wrap,它是最大宽度。使用runin,它在标题前设置缩进。否则,它会增加左边距。如果为负,则它会减少,这意味着悬垂到边距中。
  • left works differently depending on the chosen shape: with drop, leftmargin, and rightmargin, it's the title width. With wrap, it's the maximum width. With runin, it sets the indentation before the title. Otherwise, it increases the left margin. If negative, it decreases, which means overhanging into the margin.
  • beforesep设置标题前的垂直空间。
  • beforesep sets the vertical space before the title.
  • aftersep设置标题和文本之间的分隔。带有hangblockdisplay形状,它具有垂直的含义。对于runindropwrapleftmarginrightmargin形状,它是水平宽度。同样,它可能是一个负值。
  • aftersep sets the separation between the title and text. With a hang, block, and display shape, it has a vertical meaning. With a runin, drop, wrap, leftmargin, and rightmargin shape, it's a horizontal width. Again, it may be a negative value.
  • right在使用hangblockdisplay形状时增加右边距。
  • right increases the right margin when a hang, block, or display shape is used.

如果您使用星号titlesec会删除下一段的缩进。这与标准部分类似——部分标题后面的文本没有段落缩进。对于dropwraprunin,加星号的版本没有意义。

If you use an asterisk, titlesec removes the indentation of the following paragraph. That's similar to standard sections – the text that follows a section heading doesn't have paragraph indentation. With drop, wrap, and runin, the starred version has no meaning.

在我们的示例中,我们避免了章节标题后段落的缩进,并在标题前指定了30pt的空格,在标题后指定了20pt的空格。与标准课程相比,这要少一些,标准课程在章节标题上方使用50pt 。

In our example, we avoided the indentation of the paragraph that follows a chapter heading, and we specified a space of 30pt before the heading and 20pt after it. That's less compared to standard classes, which use 50pt above chapter headings.

强烈建议阅读titlesec文档以充分利用它。在其附录中,它显示了如何使用\titleformat\titlesec定义标准类中的标题。这是从复制这些定义并开始修改它们开始的好方法。

It's highly recommended to read the titlesec documentation to get the most out of it. In its appendix, it shows how the headings in standard classes would be defined with \titleformat and \titlesec. That's a great way to start by copying these definitions and beginning to modify them.

今天使用无衬线标题非常普遍。它们没有像粗体衬线标题那样沉重和古老的外观。然而,衬线文本提供了最好的可读性主体。现在由您来选择——您已经拥有了工具。

Using sans serif headings is very common today. They don't have such a heavy and ancient appearance like bold serif headings. However, serif text offers the best readability for body text. Now it's up to you to choose – you've got the tools.

在下一节中,我们将学习如何为文档添加颜色。

In the next section, we will learn how to add color to our documents.

给我们的文件上色

Coloring our documents

我们可以用颜色进一步增强我们的文本。我们还没有处理它,因为大多数人使用 LaTeX 来写严肃的书籍和文章或商业信函,其中过多的颜色可能会损害外观。但为什么不尝试一些奇特的东西呢?例如,演示文稿中的图表通常是彩色的。

We could enhance our text further with colors. We haven't dealt with it yet, because most people use LaTeX to write serious books and articles or business letters where too much color may harm the appearance. But why not try something fancy? For instance, diagrams and tables in presentations are often colorful.

我们只需要加载xcolor包:

We just need to load the xcolor package:

\usepackage{xcolor}

\usepackage{xcolor}

从现在开始,我们必须使用命令来设置文本颜色:

From now on, we have to use a command to set the text color:

\颜色{名称}

\color{name}

此命令是一个声明,可切换到指定的颜色。只需尝试\color{blue}

This command is a declaration that switches to the color that is named. Just try \color{blue}.

给一段文字着色对应的命令形式如下:

The corresponding command form to color a piece of text is as follows:

\textcolor{名称}{文本}

\textcolor{name}{text}

\textcolor隐含地添加分组;它是这样工作的:

\textcolor adds grouping implicitly; it works like this:

{\颜色{名称}文本}

{\color{name} text}

对于给文本片段着色,\textcolor是更好的选择,而\color对于由环境或大括号括起来的较长文本片段来说是一个不错的选择。

For coloring text snippets, \textcolor is the better choice, while \color would be a good choice for longer pieces of text enclosed by an environment or braces.

xcolor包提供许多现成的混合颜色;你只需要用它的名字来称呼一种颜色。文档中有大量颜色名称和样本表,您可以通过运行texdoc xcolor或在https://texdoc.org/pkg/xcolor上打开它们。

The xcolor package offers a lot of ready-mixed colors; you just need to call a color by its name. There are large tables of color names and samples in the documentation that you can open by running texdoc xcolor or on https://texdoc.org/pkg/xcolor.

xcolor提供了一种简单的混合颜色语法,如下所示:

xcolor provides an easy syntax of mixing colors, as follows:

name1!percent1!name2!percent2!name3!percent3…

name1!percent1!name2!percent2!name3!percent3…

这会将name1颜色与percent1百分比、name2颜色与percent2百分比以及name3颜色与percent3混合,依此类推。百分比相加为 100%,但您可以省略最后一个百分比,然后取 100 的剩余百分比。

This mixes the name1 color with the percent1 percentage together with the name2 color with the percent2 percentage and the name3 color with percent3, and so on. The percentages add up to 100%, but you can omit the last percentage, and then the remaining percent of 100 is taken.

这样比较容易举例理解:

That's easier to understand with examples:

  • 要获得 60% 黑色的深灰色,我们可以使用\color{black!60}
  • To have a dark gray that is 60% black, we can use \color{black!60}.
  • 要混合 40% 的红色和 60% 的黄色,我们可以使用\color{red!40!yellow}
  • To mix 40% red with 60% yellow, we can use \color{red!40!yellow}.
  • 要将 40% 的红色与 20% 的绿色和 40% 的蓝色混合,我们可以使用\color{red!40!green!20!blue}
  • To mix 40% red with 20% green and 40% blue, we can use \color{red!40!green!20!blue}.

xcolorcolortbl包一起可用于创建彩色表格,例如为单个单元格、行或列着色,或制作具有交替行颜色的表格。对于后者, LaTeX Cookbook的第 6 章设计表格中有一个配方。

xcolor together with the colortbl package can be used to create colorful tables, such as for coloring single cells, rows, or columns, or making tables with alternating row colors. For the latter, there is a recipe in LaTeX Cookbook in Chapter 6, Designing Tables.

概括

Summary

在本章中,我们使用超文本结构增强了我们的文档,包括彩色链接和用于导航的书签。我们现在可以编辑 PDF 元数据、自定义标题样式和使用颜色。

In this chapter, we enhanced our document with a hypertext structure including colored links and bookmarks for navigation. We can now edit the PDF metadata, customize our headings' styles, and use colors.

在我们的工作过程中,我们可能会遇到错误和警告。这对于高级 LaTeX 用户也很常见。下一章将为我们进行故障排除做准备。

During our work, we may encounter errors and warnings. That's common for advanced LaTeX users as well. The following chapter will prepare us for troubleshooting.

第 13 章:故障排除

Chapter 13: Troubleshooting

在排版过程中,LaTeX 可能会打印出警告信息。LaTeX 甚至可能不会产生所需的输出,而是显示错误消息。这是绝对正常的,例如,可能是由于命令名称中的小拼写错误或不平衡的大括号引起的。即使是专业的 LaTeX 排字员也必须处理错误——他们只知道如何高效地完成它。

During typesetting, it may happen that LaTeX prints out warning messages. It's even possible that LaTeX doesn't produce the desired output and shows error messages instead. That's absolutely normal and can be caused, for example, by minor typos in command names or by unbalanced braces. Even professional LaTeX typesetters have to deal with errors—they just know how to do it efficiently.

不要太担心潜在的错误——让 LaTeX 为您检查。然后你只需要在 LaTeX 指出的地方进行更正。

Don't worry too much about the potential errors—let LaTeX check it for you. Then you just need to do the corrections at the places pointed out by LaTeX.

本章准备我们做以下事情:

This chapter prepares us to do the following:

  • 理解和修复错误
  • Understanding and fixing errors
  • 处理警告
  • Handling warnings
  • 避免过时的类和包
  • Avoiding obsolete classes and packages
  • 一般故障排除
  • General troubleshooting

让我们首先解决错误处理。

Let's first tackle error handling.

技术要求

Technical requirements

您可以使用本地 LaTeX 安装,也可以在https://latexguide.org/chapter-13在线编译示例代码。

You can use a local LaTeX installation, or you can compile the example code online at https://latexguide.org/chapter-13.

该代码可在 GitHub 上找到: https: //github.com/PacktPublishing/LaTeX-Beginner-s-Guide-Second-Edition/tree/main/Chapter_13_-_Troubleshooting

The code is available on GitHub: https://github.com/PacktPublishing/LaTeX-Beginner-s-Guide-Second-Edition/tree/main/Chapter_13_-_Troubleshooting.

理解和修复错误

Understanding and fixing errors

如果 LaTeX 排版引擎遇到问题,它会发出一个错误信息。这是信息性的,旨在为您提供帮助。因此,请仔细阅读消息。除了发生错误的行号之外,LaTeX 还提供了诊断消息。

If the LaTeX typesetting engine encounters a problem, it will issue an error message. This is informative and it's intended to help you. So, read the messages carefully. Besides the line number where the error occurred, LaTeX provides a diagnostic message.

专注于第一错误信息。如果继续排版,其他错误可能只是第一个混淆编译器的结果。

Concentrate on the very first error message. If you continue typesetting, other errors might just be a consequence of the first one that confused the compiler.

让我们创建一个小的测试文档。当然,您已经遇到过那些“ Hello world! ”打印程序——我们将用 LaTeX 编写一个。虽然我们已经习惯了 TeX 和 LaTeX 单词中使用的不常见的大写字母,但我们现在将尝试看看\Latex命令是否也能正常工作:

Let's create a tiny test document. For sure, you've encountered those "Hello world!" printing programs—we shall write one in LaTeX. Though we are used to the uncommon capitalization used in the words TeX and LaTeX, we will now try and see if the \Latex command works as well:

  1. 创建一个包含这些行的新文档:

    \文档类{文章}

    \开始{文档}

    \Latex\ 说:世界您好!

    \end{文档}

  2. Create a new document containing these lines:

    \documentclass{article}

    \begin{document}

    \Latex\ says: Hello world!

    \end{document}

  3. 单击排版以编译文档。LaTeX 将停止并打印出以下消息:

    !未定义的控制序列。

    l.3 \乳胶

    \ 说:世界您好!

  4. Click on Typeset to compile the document. LaTeX will stop and print out the following message:

    ! Undefined control sequence.

    l.3 \Latex

    \ says: Hello world!

  5. 点击 TeXworks 左上角的取消图标停止编译。
  6. Click on the cancel icon in the upper-left corner of TeXworks to stop compiling.
  7. 在我们第 1 步的代码中,转到第 3 行,并将\Latex替换为\LaTeX。然后再编译。现在,LaTeX 产生了没有错误的输出:
  8. In our code from step 1, go to line 3, and replace \Latex with \LaTeX. Then compile again. Now, LaTeX produces output without an error:
图 13.1 – 更正文档的输出

图 13.1 – 更正文档的输出

Figure 13.1 – The output of the corrected document

LaTeX 命令区分大小写。因为我们不尊重这一点,LaTeX 不得不处理一个名为\Latex的宏,这是未知的。作为命令也称为控制序列,我们得到读取Undefined control sequence时出错。

LaTeX commands are case-sensitive. Because we did not respect that, LaTeX had to deal with a macro called \Latex, which is just unknown. As a command is also called a control sequence, we got an error reading Undefined control sequence.

如果 TeX 遇到错误,它会停止排版并要求用户输入。您可以按Enter键继续排版,但您可能会得到输出不正确的 PDF。最好立即取消并更正错误。

If TeX encounters an error, it stops typesetting and asks for user input. You could press the Enter key to continue typesetting, though you may get a PDF with incorrect output. It's better to cancel and correct the error immediately.

让我们分析一下三个部分错误输出:

Let's analyze the three parts of the error output:

  • 错误消息以感叹号开头,后跟问题的简短描述。
  • An error message begins with an exclamation mark, followed by a short description of the problem.
  • 然后 LaTeX 打印出出现错误的输入行的编号和出现问题的那部分行。
  • Then LaTeX prints out the number of the input line where the error was raised and the part of the line where the problem occurred.
  • 换行后,LaTeX 打印输入行的剩余部分。
  • After a line break, LaTeX prints the remaining part of the input line.

所以,你不是一个人没有线索。LaTeX 准确地告诉您需要知道的内容:

So, you are not on your own without a clue. LaTeX tells you exactly what you need to know:

  • 错误的种类
  • The kind of error
  • 错误的确切位置
  • The exact location of the error

大多数编辑器会向您显示行号或允许跳转到您输入的行号。由于您现在可以很容易地找到代码中有问题的地方,您只需要知道 LaTeX 出错的原因——这是以下部分的主题。

Most editors show you the line number or allow jumping to the line number you enter. As you can now easily find the problematic place in the code, you only need to know why LaTeX is complaining—that's the topic of the following sections.

如果您使用的是 Overleaf,有一个小警告:Overleaf 隐藏错误消息,继续编译,并在出现错误时显示输出。以下屏幕截图显示了我们的文档在 Overleaf 中存在错误:

If you are using Overleaf, there's a small caveat: Overleaf hides the error messages, continues compiling, and presents output even if there was an error. The following screenshot shows our document with the error in Overleaf:

图片 13.2 – 背页中的代码错误

图片 13.2 – 背页中的代码错误

Figure 13.2 – A code error seen in Overleaf

乍一看,我们得到我们的文件。但如果我们仔细观察,我们会看到以下内容:

At first glance, we do get our document. But if we look closer, we see the following:

  • 一开始,LaTeX这个词就不见了。
  • At the beginning, the word LaTeX is missing.
  • 输出上方有一个红色的小数字。
  • There's a small red number above the output.

红色的小数字表示存在错误,我们应该认真对待该信息。否则,正如我们在这里看到的,我们可能有一个文档丢失或输出不正确,并且在一个可能很难注意到的大文档中。

That small red number indicates that there's an error, and we should take that information seriously. Otherwise, as we saw here, we may have a document with missing or incorrect output, and in a large document that might be hard to notice.

点击红色号码,和一个窗口错误消息打开:

Click on the red number, and a window with the error message opens:

图 13.3 – 背页中的错误信息

图 13.3 – 背页中的错误信息

Figure 13.3 – An error message in Overleaf

现在我们可以看到整个错误消息,解释和位置,第 3 行。在图 13.2中,可以看到错误的第 3 行标有红叉。您可以通过单击左下角的查看原始日志来查看包含信息、错误和警告的完整日志文件。

Now we can see the entire error message, the explanation, and the location, line 3. In Figure 13.2, you can see that the erroneous line 3 is marked with a red cross. You can see the full log file with information, errors, and warnings by clicking on View Raw Logs at the bottom left.

我们现在应该仔细看看经常遇到的 TeX 和 LaTeX 错误消息。让我们在接下来的部分中通过每个主题来做到这一点。我们将从序言开始。

We shall now have a closer look at frequently encountered TeX and LaTeX error messages. Let's do this in the following sections by going through each topic. We will start with the preamble.

处理序言和文件主体

Handling the preamble and document body

序言用于文档范围设置。这里, 我们指定文档类、加载包、设置选项和定义命令。\ begin{document}命令结束序言并开始文档正文,我们可以在其中键入文本。如果我们让这个结构的一个错误,一个以下错误会发生:

The preamble is for document-wide settings. Here, we specify the document class, load packages, set options, and define commands. The \begin{document} command ends the preamble and begins the document body where we can type our text. If we make a mistake in this structure, one of the following errors will occur:

  • 缺少 \begin{document}:您很可能忘记了\begin{document}命令。但是即使您没有忘记它,也可能会发生错误。在那种情况下,序言可能有问题。具体来说,如果序言中的字符或命令产生输出,LaTeX 会引发此错误。请记住,在\begin{document}之前不允许输出。
  • Missing \begin{document}: Most likely, you might have forgotten the \begin{document} command. But the error may occur even if you did not forget it. In that case, there may be a problem in the preamble. Specifically, if a character or a command within the preamble produces output, LaTeX would raise this error. Just remember that output is not allowed before \begin{document}.
  • Can be used only in preamble : 此错误消息指的是只允许在序言中使用的命令,而不是在\begin{document}之后。例如,\usepackage只能用在序言中。将该命令向上移动到您的序言中,或将其删除。
  • Can be used only in preamble: This error message refers to a command that is only allowed to be used in the preamble, not after \begin{document}. For example, \usepackage can only be used in the preamble. Move that command upward into your preamble, or remove it.
  • 包的选项冲突:如果 LaTeX 加载包两次但选项不同,则会发生选项冲突。如果您在文档序言中有两个\usepackage{...}行表示同一个包,就会发生这种情况。如果你这样做了,通常最好将它减少到一个带有所需选项的\usepackage调用。但原因可能是隐藏的:想象一下,一个类或一个包隐式加载了某个包以及一些选项。如果你也想加载包但有不同的选项,那就有问题了。
  • Option clash for package: An option clash happens if LaTeX loads a package twice but with different options. That can happen if you have two \usepackage{…} lines for the same package in your document preamble. If you did that, it's usually better to reduce it to one \usepackage call with the desired options. But the cause might be hidden: Imagine that a class or a package implicitly loads a certain package together with some options. If you want to load the package too but with different options, there's a problem.

您可以尝试通过在为文档类指定所需选项时省略重新加载包来修复选项冲突。请记住,包继承类选项。一些包和类甚至提供在加载后设置选项的命令。例如,hyperref包提供\hypersetup{options},类似地,caption包提供\captionsetup

You could try to fix an option clash by omitting to reload the package while specifying the desired options to the document class. Remember, packages inherit class options. Some packages and classes even offer commands to set options after loading. For example, the hyperref package provides \hypersetup{options}, and similarly, the caption package offers \captionsetup.

在以下部分中,我们将查看文档正文中的常见问题。

In the following sections, we will look at common issues in the document body.

使用命令和环境

Using commands and environments

命令名称可能很容易被拼写错误或被误用。让我们检查解决 LaTeX 的常见问题:

Command names might easily be misspelled or just misused. Let's check out LaTeX's common complaints:

  • Undefined control sequence:正如我们在上一节的例子中,LaTeX 偶然发现了一个未知的命令名称。有两个可能的原因:

    A。命令名称可能拼写错误。在这种情况下,您只需更正它并重新开始排版。

    b. 命令名称是正确的,但它是由您未加载的包定义的。将\usepackage命令添加到您的序言中,它加载所需的包。

  • Undefined control sequence: As in our example in the previous section, LaTeX stumbled across an unknown command name. There are two possible reasons:

    a. The command name might be misspelled. In that case, you just need to correct it and restart the typesetting.

    b. The command name is correct, but it's defined by a package you didn't load. Add a \usepackage command to your preamble, which loads the required package.

  • Environment undefined:这类似于Undefined control sequence,但是这次我们开始一个未知的环境。同样,这可能是由拼写错误或丢失的包裹引起的——您知道如何更正它。
  • Environment undefined: This is similar to Undefined control sequence, but this time we began an unknown environment. Again, this may be caused by a misspelling or by a missing package—you know how to correct it.
  • Command already defined:当您创建一个名称已被使用的命令时会发生这种情况,例如,使用\newcommand\newenvironment。只需选择一个不同的名称。如果您真的想覆盖该命令,请改用\renewcommand\renewenvironment
  • Command already defined: This happens when you create a command with a name that's already used, for example, with \newcommand or \newenvironment. Just choose a different name. If you would really like to override that command, use \renewcommand or \renewenvironment instead.
  • Missing control sequence inserted : 控制序列已被预期但没有出现。一个常见的原因是使用\newcommand\renewcommand\providecommand,但没有指定命令名称作为其第一个参数。
  • Missing control sequence inserted: A control sequence has been expected but didn't appear. A common cause is using \newcommand, \renewcommand, or \providecommand, but not specifying a command name as its first argument.
  • 命令参数中的 \verb 非法:用于生成逐字文本的\verb命令是一个微妙的命令;它不能在命令或环境的参数中使用。examplep包提供了在这些地方使用逐字文本的命令。
  • \verb illegal in command argument: The \verb command for producing verbatim text is a delicate one; it cannot be used within arguments of commands or environments. The examplep package offers commands for using verbatim text in such places.

在这个列表中,第一个错误可能是最常发生的错误,因为输入错误就像忘记加载包一样容易发生。

Of this list, the very first error is probably the one that happens most often, since typing errors happen as easily as forgetting to load a package.

写数学公式

Writing math formulas

当 LaTeX 遇到排版时出错数学表达式,可能会出现以下错误消息之一:

When LaTeX encounters an error during typesetting math expressions, one of the following error messages can occur:

  • 缺少 $ inserted:有很多命令只能在数学模式下使用。想想符号;他们中的大多数需要数学模式。如果 LaTeX 不在数学模式下,但遇到这样的符号,它会停止并打印出该错误。通常,我们可以通过插入缺失的$来解决此类错误。忘记开始或结束数学模式是最常见的错误之一。另外,请记住您不能在数学表达式中使用分段符。这意味着数学表达式中的空行是非法的;我们必须在空白行之前结束数学模式。
  • Missing $ inserted: There are a lot of commands that may only be used in math mode. Just think of symbols; most of them require math mode. If LaTeX is not in math mode, but encounters such a symbol, it stops and prints out that error. Usually, we can resolve such errors by inserting that missing $. Forgetting to start or end math mode is one of the most frequent mistakes. Also, remember that you cannot use paragraph breaks inside a math expression. This means that blank lines within a math expression are illegal; we have to end math mode before the blank line.
  • 命令在数学模式下无效:某些命令在数学公式中不适用。在这种情况下,请在数学模式之外使用命令。
  • Command invalid in math mode: Some commands are not applicable within math formulas. In that case, use the command outside math mode.
  • Double subscript, double superscript : 两个连续的下标或上标不能被编译。例如,在$a_n_1$中,LaTeX 无法决定a_n是否应该有一个下标1,或者a是否应该有一个下标n_1。要纠正这个问题,请用大括号将它们分组,例如$a_{n_1}$
  • Double subscript, double superscript: Two subsequent subscripts or superscripts cannot be compiled. For example, in $a_n_1$, LaTeX cannot decide if a_n should have a subscript 1, or if a should have a subscript n_1. To correct that, group them by braces, such as in $a_{n_1}$.
  • 错误的数学环境定界符:这可能是非法嵌套数学模式的结果。如果您已经处于数学模式,则不得启动数学模式。例如,不要在方程式环境中使用\[。同样,您不得在开始数学模式之前结束它。确保您的数学模式定界符匹配并且大括号是平衡的。
  • Bad math environment delimiter: This can be a consequence of illegally nesting math mode. You must not start math mode if you are already inside math mode. For example, don't use \[ within an equation environment. Similarly, you must not end the math mode before you start it. Ensure that your math mode delimiters match and that braces are balanced.

第 9 章,编写数学公式中,我们学习了如何避免此类错误。

In Chapter 9, Writing Math Formulas, we learned how to avoid such errors.

使用文件

Working with files

如果 LaTeX 打不开一个文件,它可能会引发以下错误之一:

If LaTeX cannot open a file for you, it can raise one of the following errors:

  • 找不到文件:LaTeX 试图打开一个不存在的文件。可能,您执行了以下操作之一:

    A。使用\include\input来包含一个.tex文件,但具有指定名称的文件不存在。

    b. 尝试使用不存在的包或拼写错误的包名称。包由.sty文件扩展名识别。

    C。使用了不存在或名称不同的文档类。类文件的扩展名为.cls

    只需更正输入文档中的文件名或重命名文件即可。

  • File not found: LaTeX tried to open a file that doesn't exist. Possibly, you did one of the following:

    a. Used \include or \input to include a .tex file but a file with the specified name doesn't exist.

    b. Tried to use a nonexistent package or misspelled the package's name. Packages are recognized by the .sty file extension.

    c. Used a document class that doesn't exist or just has a different name. Class files have the extension .cls.

    Just correct the filename in your input document or rename the file.

  • \include 不能嵌套:我们在第 11 章开发大型文档中了解到,我们不能在自己被包含的文件中使用\include 。相反,我们在这些文件中使用\input

    关于文件名

    最好避免特殊字符和文件名中的空格。LaTeX 和操作系统都可能存在文件名中不常见字符的问题,因此最好坚持使用常见的字母、数字、破折号和下划线。

  • \include cannot be nested: We learned in Chapter 11, Developing Large Documents, that we cannot use \include within files that are being included themselves. Instead, we use \input within such files.

    Regarding filenames

    It's good to avoid special characters and spaces in filenames. Both LaTeX and the operating system may have an issue with unusual characters in filenames, so it's good to stick to the common letters, digits, dashes, and underscores.

创建表和数组

Creating tables and arrays

诚然,表格数组环境没有最简单的句法。那些&\\可能很容易放错地方,这会导致 LaTeX 报错。此外,我们必须小心格式化参数。这些是您可能会看到的关于环境参数的错误:

Admittedly, tabular and array environments don't have the simplest syntax. Those & and \\ might easily be misplaced, which causes LaTeX to complain. Further, we have to be careful with the formatting arguments. These are the possible errors you might see regarding arguments to the environment:

  • 数组 arg 中的非法字符:在表格数组环境的参数中,您可以指定列格式。您排列lcrp@等字符和{1cm}等宽度参数。如果你使用任何没有这种含义的字符,LaTeX 会告诉你。这同样适用于\multicolumn的格式化参数。
  • Illegal character in array arg: In the argument to a tabular or an array environment, you can specify the column formatting. You line up characters such as l, c, r, p, @, and width arguments such as {1cm}. If you use any character that doesn't have such a meaning, LaTeX will tell you. The same applies to the formatting argument of \multicolumn.
  • Missing p-arg in array arg:比上一条消息更具体一些,这告诉我们缺少p选项的宽度参数。用{1cm}等宽度补充p或将p更改为另一个选项,例如lcr
  • Missing p-arg in array arg: A bit more specific than the previous message, this tells us that the width argument to the p option is missing. Supplement p with a width such as {1cm} or change p to another option, such as l, c, or r.
  • Missing @-exp in array arg :缺少@选项后的表达式。您只需要在花括号中添加它,或删除@选项。
  • Missing @-exp in array arg: The expression after the @ option is missing. You just need to add it, in curly braces, or remove the @ option.

现在我们来看看有关表体的潜在错误消息:

Now we shall take a look at the potential error messages concerning the table body:

  • Misplaced alignment tab character & : 如您所知,与号字符具有分栏的特殊意义在一行表格或数组环境中。如果不小心用在常规文本中,就会出现这个错误。如果您希望在输出中出现 & 符号,请键入\& 。
  • Misplaced alignment tab character &: As you know, the ampersand character has the special meaning of separating columns in a row of a tabular or array environment. If you accidentally use it in regular text, this error will appear. Type \& if you desire an ampersand symbol in the output.
  • 额外的对齐制表符已更改为 \cr:如果您使用太多用于分隔列的对齐制表符&,则会发生这种情况。例如,对于两列,我们不能使用四个&字符作为列分隔符。如果我们忘记添加结束一行的\\ ,就会发生这样的错误。
  • Extra alignment tab has been changed to \cr: This happens if you use too many alignment tab characters &, which are for dividing columns. For example, with two columns, we cannot have four & characters as column dividers. Such an error can happen if we forget to add \\, which ends a row.

第 6 章创建中,我们讨论了避免此类错误的正确语法。

In Chapter 6, Creating Tables, we discussed the proper syntax to avoid such errors.

使用列表

Working with lists

列表遵循特定的结构,不能无限嵌套。在某些时候,LaTeX 可能会报错,例如以下错误消息:

Lists follow a specific structure and cannot be endlessly nested. At some point, LaTeX may complain, such as in the following error messages:

  • 嵌套太深:我们最多可以嵌套一个列表的四层。如果我们混合列表类型,我们最多可以达到六个级别。但如果我们比 LaTeX 接受的更进一步,我们将收到此错误消息。想想你是否真的需要深度嵌套。如果是这种情况,您可以考虑对外部级别使用分段命令,例如\paragraph\subsubsection
  • Too deeply nested: We can nest up to four levels of a list. If we mix list types, we can go up to six levels. But if we go further than what LaTeX accepts, we will get this error message. Think over if you really need deep nesting. If this is the case, you could consider using sectioning commands such as \paragraph or \subsubsection for outer levels.
  • 出了点问题——可能缺少 \item:缺少\item命令。我们在逐项列表枚举列表中可能有简单的文本。然后我们需要在该文本之前插入一个\item命令。
  • Something's wrong--perhaps a missing \item: An \item command is missing. We may have simple text in an itemize or enumerate list. Then we need to insert an \item command before that text.

第 4 章创建列表中,我们学习了正确的列表语法。

In Chapter 4, Creating Lists, we learned the proper list syntax.

使用浮动图形和表格

Working with floating figures and tables

第 5 章包括图像)和第 6 章创建表)中,我们学会了插入图和表以及如何调整它们的位置。如果您使用大量浮动对象,即图形或表格,您可能会遇到此错误:Too many unprocessed floats

In Chapter 5, Including Images, and Chapter 6, Creating Tables, we learned about inserting figures and tables and how to adjust their placement. If you use a lot of floating objects, that is, figures or tables, you might encounter this error: Too many unprocessed floats.

如果您使用浮动对象,而 LaTeX 找不到合适的位置,因为可能没有空间,LaTeX 会保存该对象以供以后放置。如果这种情况经常发生,LaTeX 的浮动对象空间可能会变满,因此会出现此错误。可以通过以下方式解决:

If you use a floating object and LaTeX doesn't find an appropriate place as there might be no space, LaTeX saves the object for later placement. If that happens a lot, LaTeX's room for floating objects may get full, so this error appears. It may be solved as follows:

  • 通过向图形表格环境添加放置选项,例如[htbp!],从而降低它们的放置要求
  • By adding placement options, such as [htbp!] to the figure and table environments, thus lowering their placement requirements
  • 通过插入一个\clearpage来在合适的地方清除浮动,或者甚至更聪明:\afterpage{\clearpage}afterpage
  • By inserting a \clearpage to flush out the floats at a suitable place, or perhaps even cleverer: \afterpage{\clearpage} with the afterpage package

在最后一节中,我们将看看其他可能的错误情况。

In the final section, we take a look at other possible error situations.

一般语法错误

General syntax errors

正如任何标记或编程语言一样,LaTeX 的文档必须遵循语法。例如,大括号和分隔符必须匹配。如果有错误,LaTeX 会指出:

Just as with any markup or programming language, LaTeX's documents have to follow a syntax. For example, braces and delimiters have to match. If there's a mistake, LaTeX will point to it:

  • Missing { inserted, missing } inserted:虽然它看起来可能是由不平衡的括号引起的,但它可能是因为 TeX 的混淆。最有可能的是,错误发生在 LaTeX 指出错误的地方之前。因此,请彻底检查使用的语法。
  • Missing { inserted, missing } inserted: Though it reads like it might be caused by unbalanced braces, it may be because of a confusion of TeX. Most likely, the error occurred before the place where the error is pointed out by LaTeX. So, check the syntax used thoroughly.
  • Extra }, or forgotten $ : 这一次,大括号不平衡有问题,或者数学模式定界符没有正确匹配。您需要更正匹配。
  • Extra }, or forgotten $: This time, there's a problem with unbalanced braces, or math mode delimiters don't match correctly. You need to correct the matching.
  • There's no line here to end : 在垂直模式下段落之间使用\\\newline没有意义,会导致此错误。不要试图通过写\\来获得更多的垂直空间。请改用\vspace或其他跳过命令,例如\bigskip\medskip\smallskip。例如,我们可以使用\vspace{\baselineskip}生成一个空行。
  • There's no line here to end: Using \\ or \newline between paragraphs in vertical mode is not meaningful and causes this error. Don't try to get more vertical space by writing \\. Use \vspace instead, or other skip commands such as \bigskip, \medskip, or \smallskip. For instance, we can produce a blank line with \vspace{\baselineskip}.

经常的TeX 和 LaTeX 的问题列表,称为TeX FAQ,列出错误消息和解释和建议。它是可在https://texfaq.org/#errors获得。

The frequently asked questions list for TeX and LaTeX, called TeX FAQ, lists error messages together with explanations and suggestions. It's available at https://texfaq.org/#errors.

一旦我们修复了所有可能发生的错误,文档中可能仍然存在一些缺陷。如果发现潜在问题,LaTeX 会打印出警告。在下一节中,我们将看到如何处理它们。

Once we fix all errors that may have occurred, there may still be some flaws in the document. LaTeX prints out warnings if it sees a potential issue. In the next section, we will see how to deal with them.

处理警告

Handling warnings

警告信息供您参考。它们并不总是指向严重的问题,但通常最好仔细阅读这些提示并采取相应的措施。这可能会改进您的文档。

Warning messages are for your information. They don't always point to a severe problem, but often it's a good idea to read these tips carefully and act accordingly. This may improve your document.

我们现在将对此进行测试。假设我们要强调无衬线字体的文本。我们希望结果是斜体无衬线文本。

We will test this now. Let's say we want to emphasize text that is in a sans-serif font. We expect italic sans-serif text as a result.

让我们试试这个:

Let's try this:

  1. 以我们的“ Hello world! ”为例,将其修改为:

    \文档类{文章}

    \renewcommand{\familydefault}{\sfdefault}

    \开始{文档}

    \emph{世界,您好!}

    \end{文档}

  2. Take our "Hello world!" example and modify it this way:

    \documentclass{article}

    \renewcommand{\familydefault}{\sfdefault}

    \begin{document}

    \emph{Hello world!}

    \end{document}

  3. 编译。LaTeX 将在日志文件中打印出一条警告:

    LaTeX 字体警告:字体形状“OT1/cmss/m/it”的大小 <10> 不可用

    (字体)字体形状“OT1/cmss/m/sl”尝试改为输入第 4 行。

  4. Compile. LaTeX will print out a warning in the log file:

    LaTeX Font Warning: Font shape `OT1/cmss/m/it' in size <10> not available

    (Font) Font shape `OT1/cmss/m/sl' tried instead on input line 4.

  5. 检查输出:
  6. Check the output:
图 13.4 – 倾斜形状而不是斜体

图 13.4 – 倾斜形状而不是斜体

Figure 13.4 – Slanted shape instead of italic shape

\ familydefault代表 LaTeX 文档中使用的默认字体系列。对于这个宏,我们指定了\sfdefault值,这意味着默认的无衬线字体。这只是意味着 sans-serif 现在是默认字体,无论选择了哪种字体。可以想象,其他可能的值是\rmdefault\ttdefault。通过更改\familydefault,我们不必一次又一次地编写\sffamily 。

The \familydefault macro stands for the default font family used in the LaTeX document. For this macro, we specified the \sfdefault value, which means the default sans-serif font. This simply means that sans-serif is now the default, no matter which font has been chosen. As you can imagine, other possible values are \rmdefault and \ttdefault. By changing \familydefault, we don't have to write \sffamily again and again.

但是后来我们强调了我们的文字并得到了警告。讯息只是意味着在默认的OT1字体编码中没有Computer Modern Sans Serif ( cmss ) 字体,中等粗细 ( m ) 和斜体 ( it ) ,大小为10磅。此外,LaTeX 告诉我们它是如何尝试修复这个问题的——它没有选择斜体,而是选择了倾斜的形状。这还不算太糟糕——至少它看起来很相似,并且产生了输出。

But then we emphasized our text and got a warning. The message simply means that there's no Computer Modern Sans Serif (cmss) font in the default OT1 font encoding, in medium weight (m) and italic shape (it) in 10pt size. Furthermore, LaTeX told us how it tried to repair the problem – instead of italics, it chose a slanted shape. That's not too bad – at least it looks similar, and the output is produced.

这基本上是警告发生时发生的情况:LaTeX 通知我们潜在的问题或缺点,但它会尝试选择最佳替代方案并继续排版。较长的文档产生数十条警告并不少见,最常见的是处理水平或垂直对齐。

This is basically what happens when warnings occur: LaTeX informs us about a potential problem or disadvantage, but it tries to choose the best alternative and continues typesetting. It's not uncommon that a longer document produces dozens of warnings, most often dealing with horizontal or vertical justification.

通常,如果您忽略看起来不是很严重的警告并没有什么坏处,尽管跟进它们是一个好习惯。任何希望拥有完美文档的人都会修复所有警告。这样我们就不能忽视一个潜在的问题。

Often, it doesn't hurt if you ignore warnings that don't seem very serious, though following them up is a good habit. Anyone who desires to have a perfect document fixes all warnings. This way we cannot overlook a potential problem.

在以下部分中,我们将处理经常出现的带有警告的情况。

In the following sections, we will deal with frequently occurring situations with warnings.

对齐文本

Justifying text

默认情况下,LaTeX 对齐左边距和在右边距。LaTeX 通过调整之间的空间来做到这一点单词和字母。这就是所谓的完全称义。

By default, LaTeX aligns the text both at the left margin and at the right margin. LaTeX does this by adjusting the space between words and letters. That is called full justification.

如果 LaTeX 无法做到这一点,我们可能会收到以下警告之一:

If LaTeX cannot achieve that, we may get one of the following warnings:

Overfull \hbox : 一行太长,不适合文本宽度。这可能会导致文本超出边距。这可能是由断字问题引起的,我们可以通过使用\hyphenation或插入\-来解决这个问题,正如您在第 2 章格式化文本和创建宏”中学到的那样。您可以手动换行或以其他方式润色您的文字。

Overfull \hbox: A line is too long and doesn't fit the text width. This may result in text extending past the margin. This may be caused by hyphenation problems, which we can fix by using \hyphenation or by inserting \-, as you learned in Chapter 2, Formatting Text and Creating Macros. You could break the line manually or polish your words otherwise.

  • Underfull \hbox:与之前的警告相反;一行的宽度不足以适应文本宽度,因此 LaTeX 无法实现完全对齐。如果行中没有足够的文本,这可能是由\linebreak引起的。此外,\\\newline可能会导致它,例如\\\\,因为文本对齐已被中断。
  • Underfull \hbox: The opposite of the previous warning; a line is not wide enough to fit to the text width, so LaTeX could not achieve full justification. This could be caused by \linebreak, if there's not enough text on the line. Also, \\ or \newline may cause it, such as \\\\, since the text justification has been interrupted.
  • Overfull \vbox : 页面太长,因为 TeX 无法相应地中断它。文本可能会超出底部边距。
  • Overfull \vbox: The page is too long because TeX could not break it accordingly. The text might hang out past the bottom margin.
  • Underfull \vbox : 页面上没有足够的文本。TeX 不得不过早地分页。
  • Underfull \vbox: There's not enough text on the page. TeX had to break the page too early.

第 2 章格式化文本和创建宏,我们学习了如何改进对齐方式,减少此类警告。请记住,已经加载microtype包可能会有所帮助。

In Chapter 2, Formatting Text and Creating Macros, we learned how to improve the justification, reducing such warnings. Remember, already loading the microtype package may help a bit.

\sloppy声明切换到相当宽松的排版,从而避免了许多此类警告。它的对应物是\fussy,切换回默认行为。假设您曾经想使用\sloppy,因为宽松的排版可能更拉伸间距对您来说是可以的,那么最好通过分组或使用相应的环境将其保留在本地—— \ begin{sloppypar}\end{sloppypar}

The \sloppy declaration switches to pretty relaxed typesetting, thus avoiding many such warnings. Its counterpart is \fussy, switching back to the default behavior. Suppose you ever want to use \sloppy because a relaxed typesetting with possibly more stretched spacing is okay for you, then it's better to keep it local by grouping or by using the respective environment—\begin{sloppypar}\end{sloppypar}.

此外,检查提出建议和替代方案关于l2tabu中的\sloppy ,在第 11 章开发大型文档”中提到。

Additionally, check out recommendations and alternatives regarding \sloppy in l2tabu, mentioned in Chapter 11, Developing Large Documents.

引用

Referencing

许多警告处理引用。常见错误是缺少标签或引用键或已使用两次的键,或者您只需要进行另一次排版。

Many warnings deal with referencing. Common mistakes are missing label or cite keys or keys that have been used twice, or you just need another typeset run.

可能会出现以下警告:

The following warnings can occur:

  • 标签多重定义\label\bibitem已与已使用的标签名称一起使用。使标签名称唯一。
  • Label multiply defined: \label or \bibitem has been used with a label name that's already been used. Make label names unique.
  • There were multiply-defined labels : 和之前的警告一样,但是在处理完整文档之后;两个\label命令定义了相同的标签。
  • There were multiply-defined labels: Like the previous warning, but after processing the complete document; two \label commands have defined the same label.
  • 标签可能已更改。重新运行以获得正确的交叉引用:再次排版让 LaTeX 更正引用。
  • Labels may have changed. Rerun to get cross-references right: Just typeset again to let LaTeX correct the referencing.
  • 页面上的参考 ... 未定义\ref\pageref已在没有相应的\label定义的情况下使用。在合适的地方插入\label命令。
  • Reference ... on page ... undefined: \ref or \pageref has been used without a corresponding \label definition. Insert a \label command at a suitable place.
  • Citation ... on page ... undefined : \cite命令没有相应的\bibitem命令,或者.bib文件中没有 BibTeX 键。
  • Citation ... on page ... undefined: A \cite command did not have a corresponding \bibitem command, or no BibTeX key in the .bib file.
  • 有未定义的引用或引用:处理后总结——任何\ref\cite命令都没有相应的\label\bibitem命令。
  • There were undefined references or citations: Summarizing after processing—any \ref or \cite command did not have a corresponding \label or \bibitem command.

每当您收到有关引用的警告时,最好重新运行排版。通常,这样的警告会消失,因为 LaTeX 无法在第一次运行时解析所有引用。

Whenever you get warnings regarding referencing, it's a good idea to simply rerun typesetting. Often, such warnings then disappear because LaTeX couldn't resolve all references in the first run itself.

选择字体

Choosing fonts

当 LaTeX 不能根据需要使用字体,它可能打印以下警告之一:

When LaTeX cannot use a font as needed, it may print one of the following warnings:

  • 字体形状 … 大小 <…> 不可用:您选择的字体不可用。这可能是组合字体命令导致字体不存在的结果。此外,它可能只是大小不可用。LaTeX 将选择不同的字体或大小并详细告知您该选择。
  • Font shape … in size <…> not available: You chose a font that's not available. This may be a result of combining font commands that results in a nonexistent font. Also, it could just be of an unavailable size. LaTeX will choose a different font or size and inform you about that choice in detail.
  • Some font shapes were not available, defaults substituted:如果任何所选字体不可用,LaTeX 会在处理整个文档后打印此字体。
  • Some font shapes were not available, defaults substituted: LaTeX prints this after processing the entire document if any of the chosen fonts were unavailable.

检查出现此类警告的位置,看看字体大小和形状是否适合您。否则,您可以考虑使用另一种字体,就像我们在第 10 章使用字体中所做的那样。

Check where such a warning occurs to see if the font size and shape are okay for you. Otherwise, you may consider using another font, such as we did in Chapter 10, Using Fonts.

放置图形和表格

Placing figures and tables

甚至如果没有错误,LaTeX可能放不了图或适当的表。在这样的在某些情况下,LaTeX 可能会显示以下警告之一:

Even if there is no error, LaTeX may not be able to place a figure or a table properly. In such a case, LaTeX may show one of the following warnings:

  • Float too large for page:图形或表格太大,不适合页面。它会被打印出来,但页面会变得太大。
  • Float too large for page: A figure or table is too large to fit the page. It would be printed, but the page would become too large.
  • h 浮动说明符更改为 ht:如果您将h选项指定给不适合那里的浮动图形或表格,它将被放置在下一页的顶部,并且会发出警告。!h!ht也会发生同样的情况。
  • h float specifier changed to ht: If you specified an h option to a floating figure or table that doesn't fit there, it would be placed at the top of the next page, and that warning would be issued. The same can occur for !h and !ht.

使用所有可用的放置选项,例如\begin{figure}[!htbp]\begin{table}[!htbp] ,如第 5 章中所述,包括图像,可以避免许多放置问题。

Using all available placement options such as in \begin{figure}[!htbp] or \begin{table}[!htbp], as mentioned in Chapter 5, Including Images, can avoid many placement issues.

自定义文档类

Customizing the document class

如果你使用非法的,LaTeX 可能会发出一个警告Unused global option(s)类选项。这意味着您为\documentclass指定了一个选项,该选项对于类和任何加载的包都是未知的。例如,这可能是不受支持的基本字体大小。只需检查 LaTeX 抱怨的选项。

LaTeX may issue a warning reading Unused global option(s) if you use an illegal class option. This means you specified an option to \documentclass, which is unknown to the class and any loaded package. This could be, for example, a base font size that is not supported. Just check the option that LaTeX complains about.

此外,如果包本身预见到任何问题,它们可能会打印出警告。所有这些警告旨在帮助您设计文档,因此最好逐一查看。

Also, packages themselves may print out warnings if they foresee any problem. All these warnings are intended to help you design your document, so it's good to look at each one.

即使您得到的文档没有任何错误和警告,如果您使用不再更新的包或类,它也可能不是完美的。我们将在下一节中查看一些著名的过时包。

Even if you got a document without any errors and warnings, it may not be perfect if you use packages or a class that is not updated anymore. We will look at some well-known obsolete packages in the next section.

避免过时的类和包

Avoiding obsolete classes and packages

在第 11 章的末尾,开发大型文档,我们谈到了危险的过时信息。乳胶存在了几十年,教程、示例、包和模板也是如此。许多已经完全过时了,有些甚至引用了旧的 LaTeX 标准 2.09,其中甚至不存在文档类。我们指出了救援指南l2tabu 。

At the end of Chapter 11, Developing Large Documents, we talked about the dangers of outdated information. LaTeX exists for decades, and so do tutorials, examples, packages, and templates. Many are totally outdated and some even refer to the old LaTeX standard 2.09, where even document classes didn't exist. We pointed to the definitive guide, l2tabu, that comes to the rescue.

许多问题只是因为使用过时的包而发生的。例如,一些不再维护的可能会与较新的包冲突。通常,您只需要找到推荐的过时包的后继者并使用它。

Many problems just occur because of the use of obsolete packages. For example, some that aren't maintained anymore may conflict with newer packages. Often, you just need to find the recommended successor of an obsolete package and use that.

为了帮助您解决这个问题,这里有一个显示过时软件包的简短列表以及他们各自推荐的继任者:

To help you in that matter, here's a short list showing obsolete packages and their respective recommended successors:

图 13.5 – 过时的包和推荐的继任者

图 13.5 – 过时的包和推荐的继任者

Figure 13.5 – Obsolete packages and recommended successors

那不是一成不变的。当然,你可能仍然使用所谓的过时包。即使在今天,它们也可能运作良好。但是在他们的 CTAN 包主页上查看他们的描述。通常,会有关于包是否仍然相关或过时的评论,它还会列出推荐的替代包。您可以通过以https://ctan.org/pkg/开头的 URL 访问包主页,后跟包名称,例如几何包的https://ctan.org/pkg/geometry

That's not set in stone. Of course, you may still use the so-called obsolete packages. They may work well even today. But check out their description on their CTAN package home page. Usually, there are comments regarding if the packages are still relevant or obsolete, and it also lists the recommended alternative packages. You can visit the package home page at the URL starting with https://ctan.org/pkg/ followed by the package name, such as https://ctan.org/pkg/geometry for the geometry package.

你可以找到一个更新https://latexguide.org/obsolete上该列表的版本。

You can find an updated version of that list on https://latexguide.org/obsolete.

此外,我们将在下一节继续提供一些一般性建议。

Further, we will continue with some general advice in the next section.

一般故障排除

General troubleshooting

可能会有情况我们不能仅仅通过阅读警告或错误消息并采取行动来解决问题。想象一个神秘的错误,一个无法追踪的错误位置,无法解决的引用,或者只是来自类或包的不明确的消息。

There may be situations where we cannot solve a problem simply by reading and acting on warnings or error messages. Imagine a mysterious error, an untraceable error location, irresolvable references, or just unclear messages from classes or packages.

通过 LaTeX 打印出的行号,或者通过了解我们自上次排版运行以来所做的工作来定位原因通常会有所帮助。一旦我们发现有问题的行或块,我们就可以删除或修复它。否则,它可能会变得困难。

Locating the cause by the line number printed out by LaTeX, or by knowing what we've done since the previous typesetting run, usually helps. Once we've found a problematic line or chunk, we can remove or fix it. Otherwise, it might become difficult.

这是第一个一般步骤我们可以通过:

Here are the first general steps we can work through:

  • 多编译几次。这对于正确引用、定位浮动图形、创建目录、参考书目以及表格和图形列表可能是必要的。
  • Compile several times. This may be necessary for correct referencing, positioning of floating figures, creating a table of contents, bibliographies, and lists of tables and figures.
  • 检查加载包的顺序。如果在特定包之前或之后加载某些包,例如hyperref,则效果不佳。您可能只是交换一些行来更正或测试它。
  • Check the order in which you load the packages. Some packages, such as hyperref, don't work well if loaded before or after specific packages. You may just swap some lines to correct or test that.
  • 删除辅助文件。如果发生任何奇怪的事情,有时最好删除 LaTeX 在排版期间创建的所有文件。这些文件与主文档同名,但扩展名为.aux.toc.lot.lof.bbl.idx.nav,仅举一些例子。
  • Remove auxiliary files. If anything strange happens, it's sometimes a good idea to remove all files created by LaTeX during typesetting. These files have the same name as the main document but have extensions such as .aux, .toc, .lot, .lof, .bbl, .idx, or .nav, just to name some examples.

如果问题仍然存在,我们可以尝试通过以下方式找出原因:

If the problem persists, we could try to isolate the cause as follows:

  1. 创建文档的副本。如有必要,复制整个文件夹。从现在开始,在副本上工作。
  2. Create a copy of your document. If necessary, copy the complete folder. From now on, work on the copy.
  3. 删除可能与问题无关的文档部分。
  4. Remove parts of the document that are probably not involved in the problem.
  5. 排版以确保问题仍然存在。如果是这种情况,请返回步骤 2并删除文档的另一部分。如果问题消失了,您将问题隔离在刚刚删除的部分中。在后一种情况下,恢复已删除的部分,因为它包含问题。如果文档的该部分仍然太大而无法精确定位错误,您仍然可以返回步骤 2并通过从中删除较小的部分来重试。
  6. Typeset to ensure that the problem persists. If this is the case, go back to step 2 and remove another part of the document. If the problem is gone, you isolated the problem within the part you just removed. In this latter case, restore the deleted part since it contains the issue. If that part of the document is still too big to precisely locate the error, you can still go back to step 2 and try again by removing smaller parts from within it.
  7. 重复此过程几次后,您将找到问题所在。如果没有找到,减少加载的包数,重复步骤2步骤3
  8. After some repetitions of this process, you will have located the problem. If you didn't find it, reduce the number of loaded packages, and repeat step 2 and step 3.
  9. 你会结束提供一个小而完整的示例文档来重现错误。我们称其为最小工作示例( MWE )。
  10. You will end up with a small but complete example document that reproduces the error. We call this a minimal working example (MWE).

删除或重写文档中标识的部分可能会有所帮助。如果您真的想使用该部分并想修复该错误怎么办?现在您可以用一个简短的代码示例来说明问题,您可以将该问题发布到在线 LaTeX 论坛并寻求帮助。

Removing or rewriting that identified part of your document could help. What if you really want to use that part and would like to fix that error? Now that you can show the problem with a short code example, you could post that problem to an online LaTeX forum and ask for help.

你不依赖仅针对您的编辑器向您显示的错误和警告。LaTeX 会跟踪所有信息、每个警告和每个错误。这些将收集在与您的文档同名但扩展名为.log的文件中。这是一个普通的文本文件,我们可以在任何编辑器中打开它,包括您的 LaTeX 编辑器。

You are not dependent on just the errors and warnings that your editor shows you. LaTeX keeps track of all information, each warning and every error. These will be collected in a file with the same name as your document but carrying the extension .log. This is an ordinary text file and we can open it in any editor, including your LaTeX editor.

例如,本章开头的Hello world示例的日志文件以有关 TeX 和 LaTeX 格式版本的信息开头,如下所示:

For instance, the log file for our Hello world example at the beginning of this chapter starts with information about the TeX and LaTeX format versions and looks like the following:

这是 pdfTeX,版本 3.141592653-2.6-1.40.22 (TeX Live

This is pdfTeX, Version 3.141592653-2.6-1.40.22 (TeX Live

2021) (preloaded format=pdflatex 2021.6.25) 2021 年 7 月 12 日

2021) (preloaded format=pdflatex 2021.6.25)  12 JUL 2021

00:47

00:47

进入扩展模式

entering extended mode

限制 \write18 启用。

restricted \write18 enabled.

%&-行解析已启用。

%&-line parsing enabled.

**文档

**document

(./document.tex

(./document.tex

LaTeX2e <2021-06-01> 补丁级别 1

LaTeX2e <2021-06-01> patch level 1

L3编程层 <2021-06-18>

L3 programming layer <2021-06-18>

它继续提供有关文档类、其版本和使用的类选项.clo文件的信息:

It continues with information about the document class, its version, and the used class options .clo file:

(/usr/local/texlive/2021/texmf-dist/tex/latex/base

(/usr/local/texlive/2021/texmf-dist/tex/latex/base

/文章.cls

/article.cls

文档类:文章 2021/02/12 v1.4n Standard LaTeX

Document Class: article 2021/02/12 v1.4n Standard LaTeX

文档类

document class

(/usr/local/texlive/2021/texmf-dist/tex/latex/base

(/usr/local/texlive/2021/texmf-dist/tex/latex/base

/size10.clo

/size10.clo

文件:size10.clo 2021/02/12 v1.4n 标准 LaTeX 文件(大小选项)

File: size10.clo 2021/02/12 v1.4n Standard LaTeX file (size option)

)

)

然后它显示加载的包和定义——在我们的例子中并不多:

It then shows the loaded packages and definitions – not much, in our case:

(/usr/local/texlive/2021/texmf-dist/tex/latex/l3backend

(/usr/local/texlive/2021/texmf-dist/tex/latex/l3backend

/l3backend-pdftex.def

/l3backend-pdftex.def

文件:l3backend-pdftex.def 2021-05-07 L3 后端支持:

File: l3backend-pdftex.def 2021-05-07 L3 backend support:

PDF 输出 (pdfTeX)

PDF output (pdfTeX)

\l__color_backend_stack_int=\count190

\l__color_backend_stack_int=\count190

\l__pdf_internal_box=\box50

\l__pdf_internal_box=\box50

)

)

它告诉我们何时使用或打开文件:

It tells us when it uses or opens a file:

没有文件 document.aux。

No file document.aux.

\openout1 = `document.aux'。

\openout1 = `document.aux'.

它为我们提供了字体信息:

It provides us with font information:

LaTeX 字体信息:检查输入行 2 上 OML/cmm/m/it 的默认值。

LaTeX Font Info:    Checking defaults for OML/cmm/m/it on input line 2.

LaTeX 字体信息:...输入第 2 行没问题。

LaTeX Font Info:    ... okay on input line 2.

它包含所有错误和警告:

It contains all errors and warnings:

!未定义的控制序列。

! Undefined control sequence.

l.3 \乳胶

l.3 \Latex

          \ 说:世界您好!

          \ says: Hello world!

?

!急停。

! Emergency stop.

一旦我们更正了理解和修复错误部分的第 4 步中的错误,LaTeX 就会将有关 LaTeX 性能和内存的信息添加到日志文件中:

Once we correct the error in step 4 of the Understanding and fixing errors section, LaTeX adds information about LaTeX performance and memory to the log file:

这是您使用了多少 TeX 内存:

Here is how much of TeX's memory you used:

478510 个中的 385 个字符串

385 strings out of 478510

5849585 中的 6981 个字符串字符

6981 string characters out of 5849585

5000000 内存中的 301299 个单词

301299 words of memory out of 5000000

15000+600000 中的 18443 个多字母控制序列

18443 multiletter control sequences out of 15000+600000

403430字的字体信息,共8000000个,27个字体

403430 words of font info for 27 fonts, out of 8000000

9000

for 9000

8191 中有 1141 个断字异常

1141 hyphenation exceptions out of 8191

34i,5n,41p,139b,107s 堆栈位置出

34i,5n,41p,139b,107s stack positions out of

5000i,500n,10000p,200000b,80000s

5000i,500n,10000p,200000b,80000s

</usr/local/texlive/2021/texmf-dist/fonts/type1/public/

</usr/local/texlive/2021/texmf-dist/fonts/type1/public/

amsfonts/cm/cmr10.pfb></usr/local/texlive/2021

amsfonts/cm/cmr10.pfb></usr/local/texlive/2021

/texmf-dist/fonts/type1/public/amsfonts/cm/cmr7.pfb>

/texmf-dist/fonts/type1/public/amsfonts/cm/cmr7.pfb>

日志文件通过声明结束输出大小以及一些统计数据:

The log file finishes by stating the output size as well as some statistics:

输出写在 document.pdf 上(1 页,22454 字节)。

Output written on document.pdf (1 page, 22454 bytes).

PDF统计:

PDF statistics:

1000 个中有 18 个 PDF 对象(最大 8388607)

18 PDF objects out of 1000 (max. 8388607)

1 个对象流中的 10 个压缩对象

10 compressed objects within 1 object stream

1000 个中有 0 个命名目的地(最多 500000 个)

0 named destinations out of 1000 (max. 500000)

1 字的额外内存用于 PDF 输出 out of 10000

1 words of extra memory for PDF output out of 10000

(最多 10000000)

(max. 10000000)

查看您迄今为止生成的一些文档的日志文件。其中的信息看起来非常技术性,但这可能对您进行故障排除有很大帮助。

Check out the log files of some of the documents you've produced up to now. The information therein looks very technical, but this might help you a lot in troubleshooting.

概括

Summary

本章帮助我们解决 LaTeX 文档中可能出现的问题。

This chapter prepared us to solve problems that might occur in our LaTeX document.

具体来说,我们学习了定位和修复错误、理解警告消息以及分析 LaTeX 的排版日志文件。

Specifically, we learned about locating and fixing errors, understanding warning messages, and analyzing LaTeX's typesetting log file.

纠正错误是绝对必要的。处理警告是一个很有价值的奖励。如果您遇到任何您自己无法解决的问题,请毫不犹豫地在 LaTeX Internet 论坛(例如https://latex.org )上寻求帮助。在该论坛中,我们有一个专用于本书的部分LaTeX 初学者指南,我很乐意在这里回答您的问题。

Correcting errors is absolutely necessary. Dealing with warnings is a valuable bonus. If you encounter any problem that you cannot solve on your own, don't hesitate to ask for help on a LaTeX Internet forum such as https://latex.org. In that forum, we have a section dedicated to this book, LaTeX Beginner's Guide, where I would be happy to answer your questions.

对于在线的 LaTeX 朋友来说,使用这些信息来解决您的问题通常是一件轻而易举的事情,而且肯定有很多 LaTeX 爱好者乐于帮助其他 LaTeX 用户。下一章将讨论 LaTeX 互联网论坛和许多其他在线资源。

For LaTeX friends who are online, it's often an easy task to use this information to solve your problem, and definitely, a lot of LaTeX enthusiasts have fun helping other LaTeX users. The next chapter will discuss LaTeX internet forums and many other online resources.

第 14 章:使用在线资源

Chapter 14: Using Online Resources

Internet 上有大量的 LaTeX 信息和材料,这些信息和材料已经发展了很多年。今天,由于免费和开源软件的优点,存在着一个庞大的 TeX 和 LaTeX 社区,共享知识和专业知识。

There's a vast amount of LaTeX information and material on the internet, which has grown over many years. Today, thanks to the virtues of free and open-source software, a vast TeX and LaTeX community exists, sharing knowledge and expertise.

本章将指导您浏览 Internet 上的以下资源:

This chapter will guide you through the following resources on the internet:

  • 网络论坛、问答网站和讨论区
  • Web forums, Q&A sites, and discussion boards
  • 常见问题列表
  • Lists of frequently asked questions
  • 邮件列表
  • Mailing lists
  • TeX 用户组网站
  • TeX user groups sites
  • LaTeX 软件和编辑器的网站
  • Websites for LaTeX software and editors
  • 图片库
  • Graphics galleries
  • LaTeX 博客
  • LaTeX blogs
  • 推特消息
  • Twitter messages

这里列出的许多网站都是由我维护的,并且在由德语 TeX 用户组 DANTE eV 提供财务支持的服务器上运行。我的网站的完整列表位于https://latex.net/about

Many of the websites listed here are maintained by me and run on servers that are financially supported by DANTE e.V., the German-language TeX user group. A complete list of my websites is at https://latex.net/about.

正如您所知如何浏览万维网,本章不包含实际示例。相反,让我们浏览一下 Internet,从交互式讨论站点开始。

As you know how to navigate the World Wide Web, this chapter does not contain practical examples. Instead, let's take a walk through the internet, beginning with interactive discussion sites.

网络论坛、问答网站和讨论区

Web forums, Q&A sites, and discussion boards

我们走吧直的在线生活发生的地方。我们将从论坛开始。

Let's go straight to where online life happens. We will start with forums.

Internet 论坛或网络论坛提供对讨论和支持组的简单且用户友好的访问。最初,LaTeX 是更通用的计算机论坛的子论坛中的一个主题,其中其他软件。在 LaTeX 变得越来越多之后建立了流行的、特定的 LaTeX 网站,我们将在以下部分讨论其中的一些网站。

Internet forums, or web forums, offer easy and user-friendly access to discussion and support groups. Initially, LaTeX was a topic in subforums of more general computer forums, among other software. After LaTeX became more and more popular, specific LaTeX websites were founded, some of which we will be discussing in the following sections.

LaTeX 网站

LaTeX.org

推出于2007 年 1 月,网络论坛https://latex.org/是第一个专门针对 LaTeX 的网络论坛。它分为多个子论坛,每个子论坛都处理特定的 LaTeX 主题,例如数学和科学字体和字符集,以及特定的 LaTeX 发行版或特定的 LaTeX 编辑器。

Launched in January 2007, the web forum https://latex.org/ was the first web forum dedicated to LaTeX. It's split into various subforums, each dealing with a particular LaTeX topic, such as Math and Science or Fonts and Character Sets, with a certain LaTeX distribution or a specific LaTeX editor.

参与与参与任何其他网络论坛一样简单。您无需注册即可阅读,因为它是免费提供的。仅仅为了写作,您需要注册一次,选择一个登录名和密码。然后您可以提出问题或支持其他去那里寻求帮助的用户。

Participating is as easy as in any other web forum. You don't need to register for reading, as it's freely available. Just for writing, you need to register once, choosing a login name and a password. Then you may ask questions or support other users who went there looking for help.

非常欢迎提问!它们是网站的基础。您可以通过执行以下操作来增加获得有用答案的机会:

Questions are very welcome! They are the foundation of the site. You may increase the chance of receiving helpful answers by doing the following:

  • 选择一个有意义的标题让用户有兴趣阅读你的问题
  • Choosing a meaningful header to get users interested in reading your question
  • 清楚地描述你的问题
  • Describing your problem clearly
  • 引用您收到的错误或警告消息
  • Quoting the error or warning messages you've got
  • 包括一个代码示例,它允许其他人重现问题
  • Including a code example, which allows others to reproduce the problem

后者是一种很好的方法;甚至还有一个网站在https://texfaq.org/FAQ-minxampl上解释了原因和方法。一旦问题可以重现,它就接近于被解决,即使乍一看似乎很难。熟悉 LaTeX 内核和软件包源代码的有经验的用户可以解释一些东西是如何工作的,并且可以为几乎任何问题创建解决方案。您提供问题代码;你得到解决方案代码。

The latter is an excellent approach; there's even a website explaining why and how at https://texfaq.org/FAQ-minxampl. Once a problem can be reproduced, it's close to being solved, even if it seems to be difficult at first sight. Experienced users familiar with the source code of the LaTeX kernel and packages can explain how something works and can create solutions for nearly any problem. You provide problem code; you get solution code.

有一个专用于本书的子论坛,即LaTeX 初学者指南https://latex.org/forum/viewforum.php?f =66 。在那里,你可以发表关于本书的问题或评论,我可以回答。

There is a subforum dedicated to this book, the LaTeX Beginner's Guide: https://latex.org/forum/viewforum.php?f=66. There, you can post questions or remarks on this book, and I can answer them.

Stack Exchange 上的 TeX 和 LaTeX

TeX and LaTeX on Stack Exchange

网站https://tex.stackexchange.com是一个问题回答不同于传统网络论坛的网站。在网络论坛中,人们谈论和讨论,而这个问答网站的结构更直接。有一个问题,然后是答案。除了在评论中没有讨论。

The website https://tex.stackexchange.com is a question and answer site that is different from classical web forums. While in web forums, people talk and discuss, this Q&A site has a more straightforward structure. There's a question, followed by answers. There's no discussion except in the comments.

当您发布问题时,请遵循与LaTeX.org相同的发布建议。此外,指定一些关键字,即所谓的标签,我们可以使用它们来过滤站点的内容。

When you post a question, follow the same advice regarding posting as with LaTeX.org. In addition, specify some keywords, so-called tags, which we can use to filter the site's contents.

Stack Exchange 是一个商业问答网站网络。自 2021 年起,它归技术投资者 Prosus 所有。TeX 和 LaTeX 站点,通常简称为 TeX.SE,成立于 2010 年,专门为 TeX 和 LaTeX 用户而设。

Stack Exchange is a commercial network of Q&A sites. Since 2021, it is owned by Prosus, a technology investor. The TeX and LaTeX site, often called TeX.SE for short, was founded in 2010 specifically for users of TeX and LaTeX.

由于以下原因,此 TeX 问答站点已发展成为一个易于访问的知识库:

This TeX Q&A site has developed into an easily accessible knowledge base for the following reasons:

  • 问题被标记。对于每个问题,应选择一个或多个标签来描述主题。例如,如果您的问题是关于方程的\label\ref的问题,请选择标签cross-referencingequations。这使得查找特定主题的答案变得容易。专门的专家观看他们最喜欢的标签。
  • Questions are tagged. For each question, one or more tags should be chosen, describing the subject. For example, if your question is about a problem with \label and \ref for equations, choose the tags cross-referencing and equations. This makes it easy to find answers to specific subjects. Specialized experts watch their favorite tags.
  • 我们可以对答案进行投票。用户投票反对错误信息时,他们会投票支持有用且有意义的答案。这样,最佳答案就会浮到顶部。因此,您不必通读整个多页线程来找到最佳解决方案,而这对于经典网络论坛来说是必需的。
  • We can vote on answers. Users vote helpful and meaningful answers up while they vote down misinformation. This way, the best answer floats to the top. So, you don't have to read through an entire multi-page thread to find the best solution, as is necessary for classical web forums.

标记和投票都增强了信息访问。我们可以用它来排序和优化搜索结果。

Both tagging and voting enhance information access. We can use it for sorting and refining search results.

还有一个概念叫做声誉。您不必为此担心,但也许您想知道这意味着什么。发布好的问题和有价值的答案的用户根据对他们的问题和答案的投票获得声誉点数。

There's another concept called reputation. You don't need to worry about that, but perhaps you would like to know what it means. Users who post good questions and valuable answers earn reputation points depending on the votes on their questions and answers.

一定数量的声望点可以让你超越简单的提问和回答:

A certain number of reputation points allows you to go beyond simply asking and answering:

  • 您可以创建新标签或重新标记问题。
  • You can create new tags or retag questions.
  • 广告减少了。
  • Advertising is reduced.
  • 您可以编辑其他用户的帖子。
  • You can edit other users' posts.
  • 您可以访问某些审核工具。
  • You can get access to certain moderation tools.

声誉是对用户在社区中地位的粗略衡量。高声誉意味着更高的信任度和适度的访问权限。通过这种方式,该站点由社区主持并展示了协作 wiki 的各个方面。

Reputation is a rough measurement of the user's status in the community. A high reputation means higher trust and moderation access. In that way, the site is community-moderated and shows aspects of a collaborative wiki.

对于新用户,有一个入门指南:https://tex.meta.stackexchange.com/questions/1436/welcome-to-tex-sx

For new users, there is a starter guide: https://tex.meta.stackexchange.com/questions/1436/welcome-to-tex-sx

您还可以在帮助中心找到更多信息,网址为:https://tex.stackexchange.com/help

You can also find further information in the help center at: https://tex.stackexchange.com/help.

由于 TeX.SE非常严格,并且问题与现有内容相关的内容可能会在没有答案的情况下迅速关闭,对于有任何问题的初学者来说,LaTeX.org 可能是更好的选择。

Since TeX.SE is very strict, and questions related to already existing content may quickly be closed without answers, LaTeX.org may be a better choice for beginners with any question.

其他语言的论坛

Forums in other languages

以下站点与 TeX StackExchange 非常相似:

The following sites are very similar to TeX StackExchange:

与 LaTeX.org 类似,https://golatex.de是一个关于 LaTeX 的德国网络论坛,它还在https://golatex.de/wiki上提供了一个参考 wiki 。

And similar to LaTeX.org, https://golatex.de is a German web forum on LaTeX that also provides a reference wiki at https://golatex.de/wiki.

新闻组

Usenet groups

大约1980 年,在万维网诞生很久之前,Usenet出现了。这是一个由数以千计的群组组成的讨论网络,即所谓的新闻组,每个群组都专注于一个特定的主题。毫不奇怪,有 TeX 新闻组。

Around 1980, a long time before the World Wide Web was born, the Usenet emerged. This is a discussion network that consists of many thousands of groups, so-called newsgroups, each dedicated to a specific subject. Unsurprisingly, there are TeX newsgroups.

最著名的是comp.text.tex。访问它的最简单方法是访问由 Google 托管的https://groups.google.com/g/comp.text.tex。只需使用其网络界面浏览即可。

The most famous one is comp.text.tex. The easiest way to access it is to visit https://groups.google.com/g/comp.text.tex, hosted by Google. Just browse it using its web interface.

或者,您可以安装 Usenet 阅读器程序并连接到 Usenet Web 服务器。此时,您应该熟悉 Usenet。一个很好的起点是位于https://en.wikipedia.org/wiki/Usenet的维基百科条目。您将在其中找到介绍、必要软件的链接以及进一步的阅读材料。

Alternatively, you could install a Usenet reader program and connect to a Usenet web server. At this point, you should familiarize yourself with Usenet. A great starting point is its Wikipedia entry at https://en.wikipedia.org/wiki/Usenet. There you will find an introduction, links to necessary software, and further reading.

comp.text.tex是经典的 TeX 讨论板。过去和现在,都有杰出的专家阅读和发布消息。您可以搜索和浏览超过 20 年的档案。

comp.text.tex is the classic TeX discussion board. Then and now, there are distinguished experts reading and posting messages. You can search and browse an archive reaching back over more than 20 years.

还有其他语言的新闻组。您可以查看德语或法语 Usenet如果您了解这些语言,TeX 组:

There are newsgroups in other languages as well. You could check out the German or French Usenet TeX groups if you understand those languages:

然而,随着时间的推移,Usenet 新闻组变得相当安静。如今,用户倾向于访问网络论坛和问答网站。

However, over time, Usenet newsgroups became pretty quiet. Nowadays, users tend to visit web forums and Q&A sites.

常见问题列表

Lists of frequently asked questions

现在轮到你知道去哪里寻求帮助。然而,在长期存在的在线 LaTeX 社区中,其他用户遇到与您相同问题的可能性非常高。有一堆问题一次又一次地出现。如果您发布此类问题,社区成员可能会将您指向常见问题( FAQ ) 页面。这是指这些常见问题的答案列表。以下网站托管着名的收藏:

Now you know where to ask for help. However, during the long existence of online LaTeX communities, the probability that another user encountered the same problem as you is very high. There's a bunch of questions that appear again and again. If you post such a question, the community member might point you to a Frequently Asked Questions (FAQs) page. This refers to a list of answers to these FAQs. The following websites host famous collections:

  • TeX 常见问题解答: https: //texfaq.org是一个常见问题解答由英国 TeX 用户组维护的网站。它包含数百个常见问题和经过深思熟虑的答案。它们按主题排序,并且该列表仍在增长并不断改进。
  • TeX FAQ: https://texfaq.org is an FAQ site maintained by the UK TeX Users' Group. It contains several hundred frequently asked questions and well-thought-out answers. They are sorted by topic, and that list is still growing and being continuously being improved.
  • Visual LaTeX 常见问题解答https://ctan.org/pkg/visualfaq是一个非常不同的方法。Visual FAQ 是一个 PDF 文档,包含数百个文本和图形元素,例如表格、图形、列表、脚注和数学公式。它有三十页,里面全是演示样本。除了所有文档对象外,关键位置都被标记和超链接。只需单击任何标记的对象,您就会进入相应的 TeX FAQ 条目。看一看; 这是一个奇特的界面。
  • Visual LaTeX FAQ: https://ctan.org/pkg/visualfaq is a very different approach. The Visual FAQ is a PDF document containing hundreds of textual and graphic elements such as tables, figures, lists, footnotes, and math formulas. It is thirty pages, which are full of demonstration samples. Besides all document objects, key positions are marked and hyperlinked. Just clicking on any marked object leads you to the corresponding TeX FAQ entry. Take a look; it's a fancy interface.
  • MacTeX 常见问题解答: https: //tug.org/mactex/faq/如果您是 Mac 用户,则为您量身打造。它涵盖了 MacTeX LaTeX 发行版和流行的 Mac LaTeX 编辑器 TeXShop 的安装和使用。
  • MacTeX FAQ: https://tug.org/mactex/faq/ is made for you if you are a Mac user. It covers the installation and use of the MacTeX LaTeX distribution and the popular Mac LaTeX editor TeXShop.
  • AMS-Math 常见问题解答https://www.ams.org/faq列表有关amsmath的问题和解答,最推荐的 LaTeX 数学包。
  • AMS-Math FAQ: https://www.ams.org/faq lists questions and answers relating to amsmath, the most recommended LaTeX math package.
  • LaTeX Picture FAQ : https://ctan.org/pkg/l2picfaq是为了解答而开发的关于包含图片的很多问题。例如,它处理各种图像文件格式、转换工具、图片处理和浮动图形的放置。该文档包含许多小代码示例,对于 LaTeX 初学者来说是一个方便的资源。

    由于它起源于德国 LaTeX 论坛,因此它是用德语编写的。它已被翻译成英文,但译文尚未在 2021 年出版。

  • LaTeX Picture FAQ: https://ctan.org/pkg/l2picfaq was developed for answering a lot of questions about including pictures. It deals, for example, with the various image file formats, conversion tools, picture manipulation, and placement of floating figures. The document contains a lot of small code examples and is a handy resource for a LaTeX beginner.

    As it originated in a German LaTeX forum, it's written in German. It has been translated into English, but the translation is not yet published in 2021.

  • German TeX FAQ : https://texfragen.de是德语语言的答案列表按主题排列的常见 LaTeX 问题。
  • German TeX FAQ: https://texfragen.de is a German-language list of answers to frequently asked LaTeX questions arranged by topics.

在论坛或邮件列表中提问之前先查看 FAQ 列表通常是个好主意,后者是我们的下一个主题。

It's usually a good idea to look on an FAQ list before asking in a forum or on a mailing list, the latter being our next topic.

邮件列表

Mailing lists

现在我们再来一个传统媒体:电子邮件列表。它们用于公告和讨论。如果您订阅这样的列表,您将收到来自其他订阅者的公告和讨论贡献。您可以静默接收和阅读所有消息,也可以向列表地址发送电子邮件,然后该地址将发送给所有其他订阅者。在向订阅者列表发送一般查询之前,您应该查看常见问题解答列表。

Now we come again to a traditional media: electronic mailing lists. They are used for both announcements and discussions. If you subscribe to such a list, you will receive announcements and discussion contributions from other subscribers. You could silently receive and read all the messages, and you could send e-mails to the list address, which would then be sent to all other subscribers. Before sending a general query to the list of subscribers, you should check an FAQ list.

如今,许多人更喜欢易于访问的媒体,例如网络论坛。然而,邮件列表仍然存在,只要电子邮件流行,就会一直使用。以下邮件列表可能对您有用:

Today, many people prefer easily accessible media, such as web forums. However, mailing lists still exist and will be in use as long as e-mail is popular. The following mailing lists may be handy for you:

  • texhax: https: //tug.org/mailman/listinfo/texhax是一个一般 TeX 讨论列表, comp.text.tex的同伴,成立于 1980 年代。它拥有数百名订阅者,其中不乏专家。
  • texhax: https://tug.org/mailman/listinfo/texhax is a list for general TeX discussion, a companion to comp.text.tex, established in the 1980s. It has hundreds of subscribers, and there are many experts among them.
  • tex-livehttps://tug.org/mailman/listinfo/tex-live处理 TeX Live 集合。如果如果您安装了此软件发行版,您可能有兴趣订阅以获取最新消息并阅读和撰写有关其问题的文章。
  • tex-live: https://tug.org/mailman/listinfo/tex-live deals with the TeX Live collection. If you installed this software distribution, you might be interested in subscribing to get the latest news and read and write about its issues.
  • texworkshttps://tug.org/mailman/listinfo/texworks支持 LaTeX 编辑器 TeXworks 的用户,它我们在第 1 章使用了LaTeX 入门。如果您决定稍后使用该编辑器并且对最新的构建、技巧、脚本和新闻感兴趣,您可以订阅。
  • texworks: https://tug.org/mailman/listinfo/texworks supports the user of the LaTeX editor TeXworks, which we used in Chapter 1, Getting Started with LaTeX. You may subscribe if you decide to use that editor later on and are interested in the latest builds, tricks, scripts, and news.

您可以在https://tug.org/mailman/listinfo找到更多邮件列表。有超过 60 个针对 TeX 和 LaTeX 特定主题的邮件列表,例如参考书目、断字、PostScript、pdfTeX 和开发。

There are a lot more mailing lists that you can find at https://tug.org/mailman/listinfo. There are more than 60 mailing lists for TeX and LaTeX-specific subjects such as bibliographies, hyphenation, PostScript, pdfTeX, and development.

TeX 用户组和 LaTeX 编辑器以及其他软件的开发人员经常提供邮件列表,尤其是用于公告。您可以在他们的主页上阅读相关信息,但我们现在将查看他们的一些网站。

TeX user groups and developers of LaTeX editors, and other software, often provide mailing lists, especially for announcements. You can read about that on their home pages, but we shall now look at some of their websites now.

TeX 用户组站点

TeX user group sites

TeX 用户团体是为对 TeX 和 LaTeX 感兴趣的人组织的。他们为其成员提供支持,也为一般的 TeX 和 LaTeX 用户提供支持。让我们参观一些。

TeX user groups are organizations for people interested in TeX and LaTeX. They provide support for their members but also for TeX and LaTeX users in general. Let's visit a few.

TeX 用户组

The TeX Users Group

TeX 用户组( TUG )是一个历史悠久的非营利组织。他们的网站位于https://tug.org。TUG 成立于 1980 年,一直对 TeX 的发展和普及产生重大影响。TUG 主页是通往 TeX 世界的门户,其中包含指向支持、文档和软件的链接。它在https://tug.org/interest.html上提供了大量与 TeX 相关的互联网资源。索引和大量链接向您展示了在 Internet 上获取有用资料的途径。

The TeX Users Group (TUG) is a not-for-profit organization with a very long history. Their website is at https://tug.org. Founded in 1980, the TUG always had a significant influence on the development and popularity of TeX. The TUG home page is a portal to the TeX world with links to support, documentation, and software. It hosts an extensive collection of TeX-related internet resources at https://tug.org/interest.html. An index and a substantial number of links show you the way to helpful material on the internet.

它每年出版 3 期期刊,并每年举办国际会议。它还在https://tug.org/FontCatalogue上托管了 LaTeX 字体目录,其中列出了几乎所有可用于 LaTeX 的字体。大约有十几个类别,例如无衬线字体、打字机字体和书法字体,有助于找到正确的字体。这些字体既在概览中简要显示,又通过多种样式和数学示例广泛显示。蛋糕上的樱桃是具体的代码示例。

It publishes a journal that appears three times a year, and it holds yearly international conferences. It also hosts the LaTeX Font Catalogue at https://tug.org/FontCatalogue, which lists nearly all fonts available for use with LaTeX. About a dozen categories, such as sans-serif, typewriter, and calligraphy fonts, assist in finding the correct font. The fonts are displayed both briefly in overviews but also extensively with several styles and math examples. The cherries on the cake are specific code examples.

但丁

DANTE

Deutschsprachige Anwendervereinigung TeX e。V. ( DANTE ) 是大德文为整个 TeX 世界资助项目和提供服务的 TeX 用户组。主页https://www.dante.de是一个德语用户的良好起点。

Deutschsprachige Anwendervereinigung TeX e. V. (DANTE) is a large German-language TeX users group that funds projects and provides services for the whole TeX world. The home page, https://www.dante.de, is a good starting point for German language users.

DANTE 为使用 LaTeX 软件、网络论坛、问答站点、常见问题解答、工具等运行服务器提供财务支持,如本章介绍中所述。

DANTE provides financial support for running servers with LaTeX software, web forums, Q&A sites, FAQs, tools, and more, as mentioned in the introduction of this chapter.

乳胶项目

The LaTeX project

LaTeX3 项目团队维护 LaTeX 2e 标准并开发下一版本的 LaTeX。这网站https://www.latex-project.org向用户介绍他们的工作和一般的 LaTeX,并定期发布新闻。

The LaTeX3 project team maintains the LaTeX 2e standard and develops the next version of LaTeX. The website, https://www.latex-project.org, informs users about their work and LaTeX in general and publishes news regularly.

UK TUG——英国的 TeX

UK TUG – TeX in the United Kingdom

用户组在英国支持和推广 TeX,举办会议和培训,并且是可在https://uk.tug.org获取。

This user group supports and promotes TeX in the UK, holds conferences and training, and is available at https://uk.tug.org.

其他本地用户组

Other local user groups

这里列出了来自世界各国的许多本地 TeX 用户组:

There are many local TeX user groups from various countries in the world listed here:

他们的网站通常包含本国语言的材料和有关 TeX 世界的更多信息。

Their websites often contain material in national languages and further information on the TeX world.

在下一节中,我们将了解从哪里可以获得软件、工具和软件包。

In the following section, we will see where we can get software, tools, and packages.

LaTeX 软件和编辑器的网站

Websites for LaTeX software and editors

最喜欢软件制造商和分销商、免费和开源软件项目在其主页上提供信息。

Like most software manufacturers and distributors, free and open-source software projects offer information on their home pages.

LaTeX 发行版

LaTeX distributions

今天,有是两个大型 LaTeX 发行版,都非常现代和全面,还有一些后代:

Today, there are two big LaTeX distributions, both very modern and comprehensive, plus some descendants:

  • TeX Live: https: //tug.org/texlive是一个跨平台的 LaTeX 软件集合。它运行在 Windows、Mac OS X、Linux 和其他 Unix 系统上。
  • TeX Live: https://tug.org/texlive is a cross-platform LaTeX software collection. It runs on Windows, Mac OS X, Linux, and other Unix systems.
  • MiKTeX: https: //miktex.org是一种非常用户友好且流行的 LaTeX 发行版,专门用于 Windows 操作系统。它现在也支持 Linux 和其他 Unix 系统。
  • MiKTeX: https://miktex.org is a very user-friendly and popular LaTeX distribution specifically for the Windows operating system. It now supports Linux and other Unix systems as well.
  • proTeXt: https: //tug.org/protext是一个基于 MiKTeX 的 Windows 发行版,主要侧重于易于安装。
  • proTeXt: https://tug.org/protext is a MiKTeX-based distribution for Windows that primarily focuses on easy installation.
  • MacTeX: https: //tug.org/mactex源自 TeX Live,并已针对 Mac OS X 进行了明确定制。
  • MacTeX: https://tug.org/mactex is derived from TeX Live and has been explicitly customized for Mac OS X.

大多数 Linux 版本在其存储库中提供自定义版本的 TeX Live。

Most Linux versions provide a customized version of TeX Live in their repositories.

LaTeX 编辑器

LaTeX editors

许多 LaTeX 编辑器可用,从易于使用到复杂和专业。它们中的大多数都提供语法高亮、对各种 (La)TeX 编译器的支持以及其他工具,例如 BibTeX、biber、makeindex 和 PDF 预览器。下面是要探索的列表。

There are many LaTeX editors available, from easy-to-use to complex and professional. Most of them offer syntax highlighting, support for various (La)TeX compilers, and other tools such as BibTeX, biber, makeindex, and PDF previewers. A list to explore follows.

跨平台

Cross-platform

这些编辑支持多种系统,包括 Windows、Mac OS X、Linux 和 Unix:

These editors support many systems, including Windows, Mac OS X, Linux, and Unix:

当然,Overleaf 在线编译器和编辑器也是跨平台的。

Of course, the Overleaf online compiler and editor are cross-platform as well.

视窗

Windows

添加到跨平台编辑器,有功能强大且流行的共享软件 LaTeX 编辑器,称为WinEdt。您可以在https://www.winedt.com下载它。DANTE 为其成员提供有折扣的许可证。另请参阅位于http://www.winedt.org的 WinEdt 社区站点。

In addition to the cross-platform editors, there's the powerful and popular shareware LaTeX editor called WinEdt. You can download it at https://www.winedt.com. DANTE provides licenses with a discount for its members. Also, see the WinEdt community site at http://www.winedt.org.

Linux

Linux

除了一切跨平台编辑器,有以下几种:

Besides all the cross-platform editors, there are the following:

在 Linux 上,我们通常选择适合所选窗口管理器的编辑器,KDE 或 GNOME,或者一个通用的跨平台编辑器。

On Linux, we usually choose an editor that fits the selected window manager, KDE or GNOME, or a universal cross-platform editor.

苹果操作系统

Mac OS X

TeXshopA非常流行的 Mac LaTeX编辑: https: //pages.uoregon.edu/koch/texshop/

TeXshop is a very popular Mac LaTeX editor: https://pages.uoregon.edu/koch/texshop/.

由于其出色的可用性,该编辑器被认为已将许多新用户引导至 LaTeX。TeXworks 编辑器以 TeXshop 为蓝本。

That editor is believed to have led many new users to LaTeX because of its outstanding usability. The TeXworks editor is modeled on TeXshop.

可视化编辑器 LyX

The visual editor LyX

https://www.lyx.org跨平台编辑器LyX的页面,它的外观和感觉都像一个文字处理软件,但它是基于 LaTeX 构建的。它将易于使用的图形用户界面与 LaTeX 的强大功能和结构相结合。您可以主要使用 LyX 的工具栏和菜单来开发文档,但您可以在任何时候插入 LaTeX 代码。

https://www.lyx.org is the home page of the cross-platform editor LyX, which looks and feels like a word processor software but is built on LaTeX. It combines an easy-to-use graphical user interface with the power and structure of LaTeX. You can develop documents mainly using LyX's toolbars and menus, but you may insert LaTeX code at any point.

LyX wiki 提供了广泛的https://wiki.lyx.org上的文档。

The LyX wiki offers extensive documentation at https://wiki.lyx.org.

在 LyX 主页上,您会找到下载、新闻和支持的链接。由于 LyX 非常流行,因此在https://latex.org有一个专门的 LyX 支持论坛。

On the LyX home page, you will find links for download, news, and support. As LyX is very popular, there is a LyX dedicated support forum at https://latex.org.

CTAN – 全面的 TeX 档案网络

CTAN – the Comprehensive TeX Archive Network

基于https://ctan.org的网络由全球众多服务器中的一个,其中存储了最广泛的 TeX 相关资料。CTAN 用作安装和更新 LaTeX 发行版(例如 TeX Live)的存储库。

The network based on https://ctan.org consists of many servers worldwide, which store the most extensive collection of TeX-related material. CTAN serves as a repository for installing and updating LaTeX distributions such as TeX Live.

在 CTAN 主页上,您会找到搜索功能,或者您可能只是开始浏览存档目录。我们可以在这个档案中找到几乎所有严肃的 LaTeX 包。

On the CTAN home page, you will find search features, or you may just start browsing the archive directories. We can find nearly every serious LaTeX package in this archive.

在下一节中,我们将访问专门展示示例、图像和代码的网站。

In the following section, we will visit websites dedicated to showing examples, images, and code.

图片库

Graphics galleries

在 Internet 上展示站点,尤其是使用 TeX 创建图形的站点:

There are showcase sites on the internet, especially for creating graphics with TeX:

这些网站允许通过按主题排序的 LaTeX 图形文档进行可视化浏览,并提供完整的源代码和解释。

These websites allow visual browsing through LaTeX graphics documents sorted by topic and with complete source code and explanations.

现在让我们开始个性化;我们现在将转向用户博客。

Now let's get personal; we will now turn to user blogs.

LaTeX 博客

LaTeX blogs

你是对 LaTeX 新闻和专家意见感兴趣?然后 LaTeX 博客可能会为您提供最新的 LaTeX 信息:

Are you interested in LaTeX news and expert opinions? Then LaTeX blogs may supply you with current LaTeX information:

  • https://texblog.net是我的个人博客。在这里,我撰写与 LaTeX 相关的新闻,提供提示和技巧,并提供按主题排序的结构化链接集合。
  • https://texblog.net is my personal blog. Here, I write LaTeX-related news, offer tips and tricks, and provide a structured link collection sorted by subject.
  • https://www.texdev.net由 Joseph Wright 编写,他是 LaTeX 项目的成员和各种 LaTeX 工具的作者。
  • https://www.texdev.net is written by Joseph Wright, a member of the LaTeX project and author of various LaTeX tools.
  • https://tex-talk.net/是一个 LaTeX 博客,其中一个有趣的部分充满了对 LaTeX 高级用户和开发人员的采访。
  • https://tex-talk.net/ is a LaTeX blog with an interesting section full of interviews with LaTeX power users and developers.
  • https://latex.net主要是一个文章数据库,具有多年积累的技术诀窍,但也提供类似博客的新闻帖子。
  • https://latex.net is mainly an article database with know-how accumulated over many years, but it also provides news posts like a blog.
  • http://texample.net/community是一个博客聚合器,汇总了大约 30 个 TeX 和 LaTeX 相关的博客,并会及时更新。
  • http://texample.net/community is a blog aggregator that summarizes about 30 TeX and LaTeX-related blogs and will keep you updated.
  • https://planet.dante.de是 DANTE 托管的博客聚合器,专注于德国 LaTeX 相关博客,但也包括国际博客。
  • https://planet.dante.de is a DANTE-hosted blog aggregator that focuses on German LaTeX related blogs but includes international blogs.

但更快的消息是在 Twitter 上,所以让我们接下来看看。

But even faster news is on Twitter, so let's look at that next.

推特消息

Twitter messages

受到推崇的订阅的推特账号如下:

Recommended Twitter accounts to subscribe to are as follows:

跟着标签#TeXLaTeX以获取有关 TeX 和 LaTeX 的最新消息:https://twitter.com/search?q =%23TeXLaTeX 。

Follow the hashtag #TeXLaTeX to get the latest news about TeX and LaTeX: https://twitter.com/search?q=%23TeXLaTeX.

概括

Summary

虽然您已经在本书中了解了 LaTeX 基础知识,但本章还提供了有关进一步在线阅读的概述。

While you have learned about the LaTeX fundamentals in this book, this chapter gave an overview about further reading online.

现在您知道如何查找和下载 LaTeX 软件、访问全球 LaTeX 社区知识、从博客中获取最新消息以及在遇到任何您自己无法解决的问题时在线提问。

Now you know about finding and downloading LaTeX software, accessing the worldwide LaTeX community knowledge, getting the latest news from blogs, and asking questions online if you encounter any problem that you cannot solve by yourself.

TeX 朋友会在任何社区网站上欢迎您。由于您在本书中学到了很多东西,您可能很快就会成为一名支持 LaTeX 新手的有经验的 LaTeX 用户。

TeX friends will welcome you on any community website. As you have learned much in this book, you may soon become an experienced LaTeX user who supports LaTeX novices.

你好!

Hi!

我是 Stefan,LaTeX 初学者指南的作者。我希望你喜欢阅读本书并发现它对使用 LaTeX 有所帮助。我们在 2011 年有了第一版,现在我们在 2021 年有了第二版,根据最新发展的观点重新编写。永远的乳胶!我期待 2031 年的版本——开个玩笑,那可以更早。敬请关注 https://latexguide.org 上即将到来的发展。

I’m Stefan, author of LaTeX Beginner’s Guide. I hope you enjoyed reading this book and found it helpful in using LaTeX. We had the first edition in 2011, and now we have the second edition in 2021, rewritten with a view on the newest developments. LaTeX forever! I look forward to a 2031 edition – just joking, that can be earlier. Stay tuned with upcoming developments at https://latexguide.org.

如果您可以在 Amazon 上发表评论并在此处分享您对 LaTeX 初学者指南第二版的看法,这对我(和其他潜在读者)真的很有帮助。

It would really help me (and other potential readers) if you could leave a review on Amazon sharing your thoughts on LaTeX Beginner’s Guide Second Edition here.

前往以下链接或扫描二维码留下您的评论:

Go to the link below or scan the QR code to leave your review:

https://packt.link/r/1801078653/qr

https://packt.link/r/1801078653/qr

我正在阅读每条评论。您的评论将帮助我了解您认为本书中哪些方面做得很好,以及我可以在未来的版本中改进哪些方面,因此非常感谢。

I’m reading every review. Your review will help me understand what you think worked well in this book and what I can improve for future editions, so it’s really appreciated.

最好的祝愿,

Best Wishes,

斯特凡·科特维茨

Stefan Kottwitz

Packt.com

Packt.com

订阅我们的在线数字图书馆,以全面访问 7,000 多本书籍和视频,以及行业领先的工具,帮助您规划个人发展和提升您的职业生涯。欲了解更多信息,请访问我们的网站。

Subscribe to our online digital library for full access to over 7,000 books and videos, as well as industry leading tools to help you plan your personal development and advance your career. For more information, please visit our website.

为什么要订阅?

Why subscribe?

  • 使用来自 4,000 多位行业专业人士的实用电子书和视频,减少学习时间,将更多时间用于编码
  • Spend less time learning and more time coding with practical eBooks and Videos from over 4,000 industry professionals
  • 通过专为您制定的技能计划改善您的学习
  • Improve your learning with Skill Plans built especially for you
  • 每月获得一本免费电子书或视频
  • Get a free eBook or video every month
  • 完全可搜索以便轻松访问重要信息
  • Fully searchable for easy access to vital information
  • 复制和粘贴、打印和书签内容
  • Copy and paste, print, and bookmark content

您是否知道 Packt 提供每本已出版书籍的电子书版本,并提供 PDF 和 ePub 文件?您可以在packt.com升级到电子书版本,作为印刷书客户,您有权享受电子书副本的折扣。请通过customercare@packtpub.com与我们联系,了解更多详情。

Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at packt.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at customercare@packtpub.com for more details.

www.packt.com上,您还可以阅读一系列免费技术文章,注册一系列免费时事通讯,并获得 Packt 书籍和电子书的独家折扣和优惠。

At www.packt.com, you can also read a collection of free technical articles, sign up for a range of free newsletters, and receive exclusive discounts and offers on Packt books and eBooks.

您可能喜欢的其他书籍

Other Books You May Enjoy

如果您喜欢这本书,您可能会对 Packt 的这些其他书籍感兴趣:

If you enjoyed this book, you may be interested in these other books by Packt:

乳胶食谱

乳胶食谱

LaTex Cookbook

斯特凡·科特维茨

Stefan Kottwitz

书号:978-1-78439-514-8

ISBN: 978-1-78439-514-8

  • 为您的项目选择正确的文档类以自定义其功能。
  • Choose the right document class for your project to customize its features.
  • 在全局和本地使用字体。
  • Utilize fonts globally and locally.
  • 框架、形状、排列和注释图像。
  • Frame, shape, arrange and annotate images.
  • 创建彩色图形,包括图表、流程图、条形图、树、2d 和 3d 绘图、时间线和思维导图。
  • Create colorful graphics including diagrams, flow charts, bar charts, trees, plots in 2d and 3d, time lines, and mindmaps.
  • 优化 PDF 输出并使用元数据、注释、弹出窗口、动画和填充字段丰富它。
  • Optimize PDF output and enrich it with meta data, annotations, popups, animations, and fill-in-fields.

Mermaid.js 官方指南

Mermaid.js 官方指南

The Official Guide to Mermaid.js

克努特·斯维德奎斯特和阿希什·贾恩

Knut Sveidqvist & Ashish Jain

书号:978-1-80107-802-3

ISBN: 978-1-80107-802-3

  • 了解好的和坏的文档,以及有效文档的艺术。
  • Understand good and bad documentation, and the art of effective documentation.
  • 精通轻松维护复杂图表。
  • Become well-versed with maintaining complex diagrams with ease.
  • 探索如何绘制不同类型的美人鱼图,例如流程图。
  • Discover how to draw different types of Mermaid diagrams such as flowcharts.
  • 在您的工作流程中实施美人鱼图
  • Implement Mermaid diagrams in your workflows
  • 了解如何为美人鱼图或整个站点设置主题。
  • Understand how to set up themes for a Mermaid diagram or an entire site.

Packt 正在寻找像您这样的作者

Packt is searching for authors like you

如果您有兴趣成为 Packt 的作者,请访问authors.packtpub.com并立即申请。我们与数以千计的开发人员和技术专家合作,就像您一样,帮助他们与全球技术社区分享他们的见解。您可以提出一般申请,申请我们正在招聘作者的特定热点话题,或者提交您自己的想法。

If you're interested in becoming an author for Packt, please visit authors.packtpub.com and apply today. We have worked with thousands of developers and tech professionals, just like you, to help them share their insight with the global tech community. You can make a general application, apply for a specific hot topic that we are recruiting an author for, or submit your own idea.